[Zope3-checkins] CVS: Zope3/src/zope/app/rdb/gadfly - DLispShort.py:1.1.2.2 DumbLispGen.py:1.1.2.2 SQLTESTG.py:1.1.2.2 gadfly.py:1.1.2.4 gfclient.py:1.1.2.4 gfdb0.py:1.1.2.4 gfinstall.py:1.1.2.4 gfintrospect.py:1.1.2.4 gfserve.py:1.1.2.4 gfsocket.py:1.1.2.4 gfstest.py:1.1.2.4 gftest.py:1.1.2.4 idl.py:1.1.2.4 kjParseBuild.py:1.1.2.2 kjParser.py:1.1.2.2 kjSet.py:1.1.2.2 kjbuckets0.py:1.1.2.4 kjpylint.py:1.1.2.4 pygram.py:1.1.2.4 relalg.py:1.1.2.4 remotetest.py:1.1.2.4 sqlbind.py:1.1.2.4 sqlgen.py:1.1.2.4 sqlgram.py:1.1.2.4 sqlgtest.py:1.1.2.4 sqlmod.py:1.1.2.4 sqlsem.py:1.1.2.4
Tim Peters
tim.one@comcast.net
Tue, 24 Dec 2002 21:21:47 -0500
Update of /cvs-repository/Zope3/src/zope/app/rdb/gadfly
In directory cvs.zope.org:/tmp/cvs-serv19240/src/zope/app/rdb/gadfly
Modified Files:
Tag: NameGeddon-branch
DLispShort.py DumbLispGen.py SQLTESTG.py gadfly.py gfclient.py
gfdb0.py gfinstall.py gfintrospect.py gfserve.py gfsocket.py
gfstest.py gftest.py idl.py kjParseBuild.py kjParser.py
kjSet.py kjbuckets0.py kjpylint.py pygram.py relalg.py
remotetest.py sqlbind.py sqlgen.py sqlgram.py sqlgtest.py
sqlmod.py sqlsem.py
Log Message:
Whitespace normalization, via Python's Tools/scripts/reindent.py. The
files are fixed-points of that script now. Fixed a few cases where
code relied on significant trailing whitespace (ouch).
=== Zope3/src/zope/app/rdb/gadfly/DLispShort.py 1.1.2.1 => 1.1.2.2 ===
--- Zope3/src/zope/app/rdb/gadfly/DLispShort.py:1.1.2.1 Tue Dec 24 13:04:46 2002
+++ Zope3/src/zope/app/rdb/gadfly/DLispShort.py Tue Dec 24 21:20:43 2002
@@ -1,4 +1,4 @@
-# Grammar generation
+# Grammar generation
# for lisp lists with strings, ints, vars, print, and setq
# set this variable to regenerate the grammar on each load
@@ -41,9 +41,9 @@
def VarValue( list, Context ):
varName = list[0]
if Context.has_key(varName):
- return Context[varName]
+ return Context[varName]
else:
- raise NameError, "no such lisp variable in context "+varName
+ raise NameError, "no such lisp variable in context "+varName
def NilTail( list, Context ):
return []
def AddToList( list, Context ):
@@ -66,7 +66,7 @@
Grammar.Bind( "SetqRule", DoSetq )
Grammar.Bind( "PrintRule", DoPrint )
-# This function generates the grammar and dumps it to a file.
+# This function generates the grammar and dumps it to a file.
def GrammarBuild():
import kjParseBuild
LispG = kjParseBuild.NullCGrammar()
@@ -92,7 +92,7 @@
BindRules(LispG)
return LispG
-# this function initializes the compiled grammar from the generated file.
+# this function initializes the compiled grammar from the generated file.
def LoadLispG():
import TESTLispG
# reload to make sure we get the most recent version!
@@ -114,9 +114,9 @@
########## test the grammar generation
if REGENERATEONLOAD:
- print "(re)generating the LispG grammar in file TESTLispG.py"
- Dummy = GrammarBuild()
- print "(re)generation done."
+ print "(re)generating the LispG grammar in file TESTLispG.py"
+ Dummy = GrammarBuild()
+ print "(re)generation done."
print "loading grammar as python"
LispG = LoadLispG()
@@ -157,4 +157,3 @@
"""
test7 = LispG2.DoParse1( test7str, Context)
test8 = LispG2.DoParse1( '(print (1 x d))', Context)
-
=== Zope3/src/zope/app/rdb/gadfly/DumbLispGen.py 1.1.2.1 => 1.1.2.2 ===
--- Zope3/src/zope/app/rdb/gadfly/DumbLispGen.py:1.1.2.1 Tue Dec 24 13:04:46 2002
+++ Zope3/src/zope/app/rdb/gadfly/DumbLispGen.py Tue Dec 24 21:20:43 2002
@@ -26,118 +26,118 @@
### grammar declarations
COMPILEDFILENAME = "TESTLispG2.py"
-### declare comment form(s) as regular expressions
+### declare comment form(s) as regular expressions
LISPCOMMENTREGEX = ";.*"
### declare regular expression string constants for terminals
-#integer terminal:::::::
+#integer terminal:::::::
INTREGEX = "["+string.digits+"]+"
-#string terminal::::::::
+#string terminal::::::::
STRREGEX = '"[^\n"]*"'
-#var terminal::::::::
+#var terminal::::::::
VARREGEX = "["+string.letters+"]["+string.letters+string.digits+"]*"
### declare interpretation functions for terminals
-# int interpretation function: translates string to int:
-# Could use string.atoi without the extra level of indirection
-# but for demo purposes here it is.
-#
+# int interpretation function: translates string to int:
+# Could use string.atoi without the extra level of indirection
+# but for demo purposes here it is.
+#
def intInterp( str ):
- return string.atoi(str)
+ return string.atoi(str)
-# interpretation function for strings strips off the surrounding quotes.
+# interpretation function for strings strips off the surrounding quotes.
def stripQuotes( str ):
- if len(str)<2:
- TypeError, "string too short?"
- return str[1:len(str)-1]
+ if len(str)<2:
+ TypeError, "string too short?"
+ return str[1:len(str)-1]
# interpretation function for vars just returns the recognized string
def echo(string):
- return string
+ return string
-# This function declares the nonterminals both in the
-# "grammar generation phase" and in loading the compiled
-# grammar after generation
-#
+# This function declares the nonterminals both in the
+# "grammar generation phase" and in loading the compiled
+# grammar after generation
+#
def DeclareTerminals(Grammar):
- Grammar.Addterm("int", INTREGEX, intInterp)
- Grammar.Addterm("str", STRREGEX, stripQuotes)
- Grammar.Addterm("var", VARREGEX, echo)
+ Grammar.Addterm("int", INTREGEX, intInterp)
+ Grammar.Addterm("str", STRREGEX, stripQuotes)
+ Grammar.Addterm("var", VARREGEX, echo)
### declare the rule reduction interpretation functions.
-# EchoValue() serves for Intrule and Strrule, since
-# we just want to echo the value returned by the
-# respective terminal interpretation functions.
-#
-# Parser delivers list of form [ interpreted_value ]
+# EchoValue() serves for Intrule and Strrule, since
+# we just want to echo the value returned by the
+# respective terminal interpretation functions.
+#
+# Parser delivers list of form [ interpreted_value ]
def EchoValue( list, Context ):
- if len(list)!=1:
- raise TypeError, "this shouldn't happen! (1)"
- return list[0]
-
-# for Varrule interpreter must try to look up the value
-# in the Context dictionary
-#
-# Parser delivers list of form [ var_name ]
+ if len(list)!=1:
+ raise TypeError, "this shouldn't happen! (1)"
+ return list[0]
+
+# for Varrule interpreter must try to look up the value
+# in the Context dictionary
+#
+# Parser delivers list of form [ var_name ]
def VarValue( list, Context ):
- if len(list)!=1:
- raise TypeError, "Huh? (2)"
- varName = list[0]
- if Context.has_key(varName):
- return Context[varName]
- else:
- raise NameError, "no such lisp variable in context "+varName
-
-# for an empty tail, return the empty list
-#
-# Parser delivers list of form [")"]
+ if len(list)!=1:
+ raise TypeError, "Huh? (2)"
+ varName = list[0]
+ if Context.has_key(varName):
+ return Context[varName]
+ else:
+ raise NameError, "no such lisp variable in context "+varName
+
+# for an empty tail, return the empty list
+#
+# Parser delivers list of form [")"]
def NilTail( list, Context ):
- if len(list) != 1 or list[0] != ")":
- return TypeError, "Bad reduction?"
- return []
-
-# For a full tail, add the new element to the front of the list
-#
-# Parser delivers list of form [Value, TailValue]
+ if len(list) != 1 or list[0] != ")":
+ return TypeError, "Bad reduction?"
+ return []
+
+# For a full tail, add the new element to the front of the list
+#
+# Parser delivers list of form [Value, TailValue]
def AddToList( list, Context ):
- if len(list) !=2:
- return TypeError, "Bad reduction?"
- return [ list[0] ] + list[1]
-
-# For a list, simply return the list determined by the tail
-#
-# Parser delivers list of form ["(", TailValue ]
+ if len(list) !=2:
+ return TypeError, "Bad reduction?"
+ return [ list[0] ] + list[1]
+
+# For a list, simply return the list determined by the tail
+#
+# Parser delivers list of form ["(", TailValue ]
def MakeList( list, Context ):
- if len(list)!=2 or list[0]!="(":
- raise TypeError, "Bad reduction? (3)"
- return list[1]
-
-# For a setq, declare a new variable in the Context dictionary
-#
-# Parser delivers list of form # ["(", "setq", varName, Value, ")"]
+ if len(list)!=2 or list[0]!="(":
+ raise TypeError, "Bad reduction? (3)"
+ return list[1]
+
+# For a setq, declare a new variable in the Context dictionary
+#
+# Parser delivers list of form # ["(", "setq", varName, Value, ")"]
def DoSetq( list, Context):
- if len(list) != 5\
- or list[0] != "("\
- or list[1] != "setq"\
- or list[4] != ")":
- print list
- raise TypeError, "Bad reduction? (4)"
- VarName = list[2]
- if type(VarName) != type(''):
- raise TypeError, "Bad var name? (5)"
- Value = list[3]
- # add or set the variable in the Context dictionary
- Context[ VarName ] = Value
- return Value
-
-# This function Binds the named rules of the Grammar string to their
-# interpretation functions in a Grammar.
-#
+ if len(list) != 5\
+ or list[0] != "("\
+ or list[1] != "setq"\
+ or list[4] != ")":
+ print list
+ raise TypeError, "Bad reduction? (4)"
+ VarName = list[2]
+ if type(VarName) != type(''):
+ raise TypeError, "Bad var name? (5)"
+ Value = list[3]
+ # add or set the variable in the Context dictionary
+ Context[ VarName ] = Value
+ return Value
+
+# This function Binds the named rules of the Grammar string to their
+# interpretation functions in a Grammar.
+#
def BindRules(Grammar):
Grammar.Bind( "Intrule", EchoValue )
Grammar.Bind( "Strrule", EchoValue )
@@ -147,20 +147,20 @@
Grammar.Bind( "ListRule", MakeList )
Grammar.Bind( "SetqRule", DoSetq )
-# This function generates the grammar and dumps it to a file.
-# Since it will be used only once (after debugging),
-# it probably should be put in another file save memory/load-time.
+# This function generates the grammar and dumps it to a file.
+# Since it will be used only once (after debugging),
+# it probably should be put in another file save memory/load-time.
#
-# the result returned is a Grammar Object that can be used
-# for testing/debugging purposes.
+# the result returned is a Grammar Object that can be used
+# for testing/debugging purposes.
#
-# (maybe this should be made into a generic function?)
+# (maybe this should be made into a generic function?)
def GrammarBuild():
import kjParseBuild
# initialize a Null compilable grammar to define
LispG = kjParseBuild.NullCGrammar()
-
+
# declare terminals for the grammar
DeclareTerminals(LispG)
@@ -197,8 +197,8 @@
# return the generated Grammar
return LispG
-# this function initializes the compiled grammar from
-# generated file.
+# this function initializes the compiled grammar from
+# generated file.
def LoadLispG():
import TESTLispG2
# make sure we have most recent version (during debugging)
=== Zope3/src/zope/app/rdb/gadfly/SQLTESTG.py 1.1.2.1 => 1.1.2.2 ===
--- Zope3/src/zope/app/rdb/gadfly/SQLTESTG.py:1.1.2.1 Tue Dec 24 13:04:46 2002
+++ Zope3/src/zope/app/rdb/gadfly/SQLTESTG.py Tue Dec 24 21:20:43 2002
@@ -8,23 +8,23 @@
SELECTRULES = """
## highest level for select statement (not select for update)
select-statement ::
- @R selectR :: select-statement >>
- SELECT
+ @R selectR :: select-statement >>
+ SELECT
from-clause
where-clause
group-by-clause
having-clause
## generalized to allow null from clause eg: select 2+2
@R fromNull :: from-clause >>
- @R fromFull :: from-clause >> FROM
+ @R fromFull :: from-clause >> FROM
@R whereNull :: where-clause >>
- @R whereFull :: where-clause >> WHERE
+ @R whereFull :: where-clause >> WHERE
@R groupNull :: group-by-clause >>
- @R groupFull :: group-by-clause >> GROUP BY
- @R havingNull :: having-clause >>
+ @R groupFull :: group-by-clause >> GROUP BY
+ @R havingNull :: having-clause >>
@R havingFull :: having-clause >> HAVING
- @R unionNull :: union-clause >>
- @R unionFull :: union-clause >> UNION
+ @R unionNull :: union-clause >>
+ @R unionFull :: union-clause >> UNION
"""
SELECTNONTERMS = """
@@ -36,43 +36,43 @@
column-name from-clause
"""
# of these the following need resolution
-# (select-list) (table-reference-list)
-# (search-condition) order-by-clause (column-name)
+# (select-list) (table-reference-list)
+# (search-condition) order-by-clause (column-name)
SELECTKEYWORDS = """
- SELECT FROM WHERE GROUP BY HAVING UNION DISTINCT ALL AS
+ SELECT FROM WHERE GROUP BY HAVING UNION DISTINCT ALL AS
"""
# test generation of the grammar
def BuildSQLG():
- import kjParseBuild
- SQLG = kjParseBuild.NullCGrammar()
- SQLG.SetCaseSensitivity(0)
- SQLG.Keywords(SELECTKEYWORDS)
- SQLG.Nonterms(SELECTNONTERMS)
- # no comments yet
- SQLG.Declarerules(SELECTRULES)
- print "building"
- SQLG.Compile()
- print "marshaling"
- outfile = open( MARSHALFILE, "w")
- SQLG.MarshalDump(outfile)
- outfile.close()
- return SQLG
+ import kjParseBuild
+ SQLG = kjParseBuild.NullCGrammar()
+ SQLG.SetCaseSensitivity(0)
+ SQLG.Keywords(SELECTKEYWORDS)
+ SQLG.Nonterms(SELECTNONTERMS)
+ # no comments yet
+ SQLG.Declarerules(SELECTRULES)
+ print "building"
+ SQLG.Compile()
+ print "marshaling"
+ outfile = open( MARSHALFILE, "w")
+ SQLG.MarshalDump(outfile)
+ outfile.close()
+ return SQLG
# load function
def LoadSQLG():
- import kjParser
- print "unmarshalling"
- infile = open(MARSHALFILE, "r")
- SQLG = kjParser.UnMarshalGram(infile)
- infile.close()
- return SQLG
+ import kjParser
+ print "unmarshalling"
+ infile = open(MARSHALFILE, "r")
+ SQLG = kjParser.UnMarshalGram(infile)
+ infile.close()
+ return SQLG
#### for testing
if REBUILD:
- SQLG0 = BuildSQLG()
- print " rebuilt SQLG0 as compilable grammar"
+ SQLG0 = BuildSQLG()
+ print " rebuilt SQLG0 as compilable grammar"
SQLG = LoadSQLG()
-print " build SQLG as reloaded grammar"
\ No newline at end of file
+print " build SQLG as reloaded grammar"
=== Zope3/src/zope/app/rdb/gadfly/gadfly.py 1.1.2.3 => 1.1.2.4 === (685/785 lines abridged)
--- Zope3/src/zope/app/rdb/gadfly/gadfly.py:1.1.2.3 Tue Dec 24 13:04:46 2002
+++ Zope3/src/zope/app/rdb/gadfly/gadfly.py Tue Dec 24 21:20:43 2002
@@ -9,395 +9,394 @@
verbosity = 0
class gadfly:
- """as per the DBAPI spec "gadfly" is the connection object."""
- closed = 0
- verbose = verbosity # debug!
-
- def __init__(self, databasename=None, directory=None,
- forscratch=0, autocheckpoint=1, verbose=0):
- verbose = self.verbose = self.verbose or verbose
- # checkpoint on each commit if set
- self.autocheckpoint = autocheckpoint
- if verbose:
- print "initializing gadfly instance", (\
- databasename, directory, forscratch, verbose)
- self.is_scratch = forscratch
- self.databasename=databasename
- self.directory = directory
- self.fs = None
- self.database = None
- # db global transaction id
- self.transid = 0
- if databasename is not None:
- self.open()
-
- def transaction_log(self):
- from gfdb0 import Transaction_Logger
- if self.verbose:
- print "new transaction log for", self.transid
- return Transaction_Logger(self.database.log, self.transid, self.is_scratch)
-
- # causes problems in 1.5?
- #def __del__(self):
- # """clear database on deletion, just in case of circularities"""
- # # implicit checkpoint
- # if self.verbose:
- # print "deleting gadfly instance", self.databasename
- # if not self.closed:
- # self.close()
-
- def checkpoint(self):
- """permanently record committed updates"""
- # note: No transactions should be active at checkpoint for this implementation!
- # implicit abort of active transactions!
- verbose = self.verbose
- if verbose:
- print "checkpointing gadfly instance", self.databasename
[-=- -=- -=- 685 lines omitted -=- -=- -=-]
- # only on no error...
- if success:
- # commit updates in shadow of working db (not in real db)
- if verbose: print "GFCursor: successful eval, storing results in wdb"
- database.log.flush()
- # database commit does not imply transaction commit.
- database.commit()
- else:
- if verbose:
- print \
- "GFCursor: UNSUCCESSFUL EVAL, discarding results and log entries"
- self.statement = None
- self.results = None
- self.resultlist = None
- database.log.reset()
- # handle curs.description
- self.description = None
- if len(results)==1:
- result0 = results[0]
- try:
- atts = result0.attributes()
- except:
- pass
- else:
- descriptions = list(atts)
- fluff = (None,) * 6
- for i in xrange(len(atts)):
- descriptions[i] = (atts[i],) + fluff
- self.description = tuple(descriptions)
- self.resultlist = None
-
- def setoutputsize(self, *args):
- # not implemented
- pass
-
- def setinputsizes(self, *args):
- # not implemented
- pass
-
- def pp(self):
- """return pretty-print string rep of current results"""
- from string import join
- stuff = map(repr, self.results)
- return join(stuff, "\n\n")
-
+ def pp(self):
+ """return pretty-print string rep of current results"""
+ from string import join
+ stuff = map(repr, self.results)
+ return join(stuff, "\n\n")
=== Zope3/src/zope/app/rdb/gadfly/gfclient.py 1.1.2.3 => 1.1.2.4 ===
--- Zope3/src/zope/app/rdb/gadfly/gfclient.py:1.1.2.3 Tue Dec 24 13:04:46 2002
+++ Zope3/src/zope/app/rdb/gadfly/gfclient.py Tue Dec 24 21:20:43 2002
@@ -39,7 +39,7 @@
(None for non-queries, or list of tuples).
See gfstest.py for example usage.
-
+
SCRIPT INTERPRETATION:
Server maintenance utilities
@@ -70,14 +70,14 @@
from string import atoi
port = atoi(port)
if len(argv)>4:
- machine = argv[4]
+ machine = argv[4]
else:
- machine = None
+ machine = None
print action, port, admin_password, machine
if action not in ["shutdown", "restart", "checkpoint"]:
- print "bad action", action
- print
- return
+ print "bad action", action
+ print
+ return
dosimple(action, port, admin_password, machine)
done=1
finally:
@@ -87,7 +87,7 @@
def dosimple(action, port, pw, machine=None):
import socket
if machine is None:
- machine = socket.gethostname()
+ machine = socket.gethostname()
conn = gfclient("admin", port, pw, machine)
action = getattr(conn, action)
print action()
@@ -124,7 +124,7 @@
class gfclient:
closed = 0
-
+
def __init__(self, policy, port, password, machine=None):
import socket
self.policy = policy
@@ -133,21 +133,21 @@
if machine is None:
machine = socket.gethostname()
self.machine = machine
-
+
def open_connection(self):
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#print type(sock), sock
sock.connect((self.machine, self.port))
return sock
-
+
def send_action(self, action, arguments, socket):
gfsocket.send_certified_action(
self.policy, action, arguments, self.password, socket)
-
+
def checkpoint(self):
return self.simple_action(CHECKPOINT)
-
+
def simple_action(self, action, args=()):
"""only valid for admin policy: force a server checkpoint"""
sock = self.open_connection()
@@ -155,31 +155,31 @@
data = gfsocket.recv_data(sock)
data = gfsocket.interpret_response(data)
return data
-
+
def restart(self):
"""only valid for admin policy: force a server restart"""
return self.simple_action(RESTART)
-
+
def shutdown(self):
"""only valid for admin policy: shut down the server"""
return self.simple_action(SHUTDOWN)
-
+
def close(self):
self.closed = 1
-
+
def commit(self):
# right now all actions autocommit
pass
-
+
# cannot rollback, autocommit on success
rollback = commit
-
+
def cursor(self):
"""return a cursor to this policy"""
if self.closed:
raise ValueError, "connection is closed"
return gfClientCursor(self)
-
+
class gfClientCursor:
@@ -189,16 +189,16 @@
def __init__(self, connection):
self.connection = connection
-
+
# should add fetchone fetchmany
def fetchall(self):
return self.results
-
+
def execute(self, statement=None, params=None):
con = self.connection
data = con.simple_action(EXECUTE_STATEMENT, (statement, params))
(self.description, self.results) = data
-
+
def execute_prepared(self, name, params=None):
con = self.connection
data = con.simple_action(EXECUTE_PREPARED, (name, params))
@@ -206,12 +206,12 @@
self.description = self.results = None
else:
(self.description, self.results) = data
-
+
def setoutputsizes(self, *args):
pass # not implemented
-
+
def setinputsizes(self):
pass # not implemented
-
+
if __name__=="__main__":
main()
=== Zope3/src/zope/app/rdb/gadfly/gfdb0.py 1.1.2.3 => 1.1.2.4 === (2547/2647 lines abridged)
--- Zope3/src/zope/app/rdb/gadfly/gfdb0.py:1.1.2.3 Tue Dec 24 13:04:46 2002
+++ Zope3/src/zope/app/rdb/gadfly/gfdb0.py Tue Dec 24 21:20:43 2002
@@ -14,20 +14,20 @@
def checksum(string):
from md5 import new
return new(string).digest()
-
+
def recursive_dump(data, prefix="["):
"""for debugging"""
from types import StringType
- if type(data) is StringType:
- #print prefix, data
- return
+ if type(data) is StringType:
+ #print prefix, data
+ return
p2 = prefix+"["
try:
for x in data:
recursive_dump(x, p2)
except:
print prefix, data
-
+
def checksum_dump(data, file):
"""checksum and dump marshallable data to file"""
#print "checksum_dump", file
@@ -44,10 +44,10 @@
checkpair = load(file)
(check, storage) = checkpair
if checksum(storage)!=check:
- raise StorageError, "data load checksum fails"
+ raise StorageError, "data load checksum fails"
data = loads(storage)
return data
-
+
def backup_file(filename, backupname):
"""backup file, if unopenable ignore"""
try:
@@ -59,946 +59,946 @@
f = open(backupname, "wb")
f.write(data)
f.close()
-
+
def del_file(filename):
"""delete file, ignore errors"""
from os import unlink
[-=- -=- -=- 2547 lines omitted -=- -=- -=-]
+ op
+ if verbose:
+ print "recovery successful: clearing log file"
+ self.clear()
+ if restart:
+ if verbose:
+ print "recreating empty log file"
+ self.startup()
+
+ def read_records(self, file):
+ """return log record as (index, (tid, op)) list"""
+ verbose = self.verbose
+ if verbose: print "reading log records to error"
+ import sys
+ records = {}
+ from sqlsem import deserialize
+ count = 0
+ while 1:
+ try:
+ data = checksum_undump(file)
+ except:
+ if verbose:
+ print "record read terminated with error", len(records)
+ print sys.exc_type, sys.exc_value
+ break
+ (transactionid, serial) = data
+ operation = deserialize(serial)
+ records[count] = (transactionid, operation)
+ if verbose:
+ print count, ": read for", transactionid
+ print operation
+ count = count+1
+ if verbose: print len(records), "records total"
+ records = records.items()
+ records.sort()
+ return records
+
+ def dump(self):
+ verbose = self.verbose
+ self.shutdown()
+ print "dumping log"
+ self.verbose = 1
+ try:
+ file = open(self.filename, "rb")
+ except:
+ print "DUMP FAILED, cannot open", self.filename
+ else:
+ self.read_records(file)
+ self.verbose = verbose
+ self.restart()
=== Zope3/src/zope/app/rdb/gadfly/gfinstall.py 1.1.2.3 => 1.1.2.4 ===
--- Zope3/src/zope/app/rdb/gadfly/gfinstall.py:1.1.2.3 Tue Dec 24 13:04:46 2002
+++ Zope3/src/zope/app/rdb/gadfly/gfinstall.py Tue Dec 24 21:20:43 2002
@@ -48,20 +48,19 @@
force = 0
#print argv
if len(argv)>1 and argv[1]=="force":
- force = 1
+ force = 1
if not force:
- try:
- sql = getSQL()
- except:
- print "exception", sys.exc_type, sys.exc_value
- print "during load of SQL grammar structures."
- print "Apparently the SQL grammar requires regeneration"
- force = 1
+ try:
+ sql = getSQL()
+ except:
+ print "exception", sys.exc_type, sys.exc_value
+ print "during load of SQL grammar structures."
+ print "Apparently the SQL grammar requires regeneration"
+ force = 1
if force:
- print "now generating parser structures (this might take a while)..."
- #where = cwd + "/" + marfile
- print "building in", where
- sql = BuildSQL(where)
+ print "now generating parser structures (this might take a while)..."
+ #where = cwd + "/" + marfile
+ print "building in", where
+ sql = BuildSQL(where)
print
print "done."
-
=== Zope3/src/zope/app/rdb/gadfly/gfintrospect.py 1.1.2.3 => 1.1.2.4 ===
--- Zope3/src/zope/app/rdb/gadfly/gfintrospect.py:1.1.2.3 Tue Dec 24 13:04:46 2002
+++ Zope3/src/zope/app/rdb/gadfly/gfintrospect.py Tue Dec 24 21:20:43 2002
@@ -7,48 +7,48 @@
class RemoteView(gfdb0.View):
"""Virtual superclass. See text for methods and members to define."""
-
+
# Usually redefine __init__
def __init__(self):
pass
-
+
# set static (static=1) or dynamic (static=0)
# for static tuple seq is generated once per load
# for non-static tuple seq is regenerated once per query
# which uses the view.
static = 0
-
+
# define the column_names
column_names = ['Column1']
-
+
# define the row generator
def listing(self):
"""return list of values (1 column)
or list of tuples of values (>1 column).
size of elts should match number of columns."""
return [0]
-
+
# possibly redefine __repr__ and irepr
def __repr__(self):
return "<Remote View %s at %s>" % (self.__class__, id(self))
-
+
irepr = __repr__
-
+
# for introspective methods possibly redefine relbind
def relbind(self, db, atts):
return self
-
+
### don't touch the following unless you are a guru!
cached_rows = None
-
+
def uncache(self):
if self.static: return
self.cached_rows = None
-
+
def attributes(self):
from string import upper
return map(upper, self.column_names)
-
+
def rows(self, andseqs=0):
cached_rows = self.cached_rows
if cached_rows is None:
@@ -69,27 +69,27 @@
"""static one row one column view for testing.
(Inspired by Oracle DUAL relation)."""
# trivial example extension view
-
+
static = 1
-
+
column_names = ['Column1']
-
+
def listing(self):
return [0]
-
+
class DictKeyValueView(RemoteView):
"""Less trivial example. Dict keys/values converted to strings"""
-
+
static = 0 # regenerate in case dict changes
-
+
column_names = ["key", "value"]
-
+
mapstring = 1
-
+
def __init__(self, dict=None):
if dict is None: dict = {}
self.dict = dict
-
+
def listing(self):
items = self.dict.items()
if self.mapstring:
@@ -98,13 +98,13 @@
return map(mapper, items)
else:
return items
-
+
class RelationsView(DictKeyValueView):
"""list of relations and whether they are views."""
-
+
column_names = ["table_name", "is_view"]
mapstring = 0
-
+
def relbind(self, db, atts):
rels = db.rels
dict = {}
@@ -112,14 +112,14 @@
dict[relname] = rels[relname].is_view
self.dict = dict
return self
-
+
class IndicesView(DictKeyValueView):
"""list of indices and relations they index"""
-
+
column_names = ["index_name", "table_name", "is_unique"]
-
+
mapstring = 0
-
+
def relbind(self, db, atts):
rels = db.rels
dict = {}
@@ -131,7 +131,7 @@
dict[index.name] = (relname, index.unique)
self.dict = dict
return self
-
+
def listing(self):
L = []
dict = self.dict
@@ -139,23 +139,23 @@
for k in keys:
L.append( (k,) + dict[k] )
return L
-
+
class DataDefsView(DictKeyValueView):
"""Data defs (of non-special views) and definition dumps."""
-
+
column_names = ["name", "defn"]
-
+
mapstring = 1
-
+
def relbind(self, db, atts):
self.dict = db.datadefs
return self
-
+
class ColumnsView(RemoteView):
"""table_names and columns therein."""
-
+
column_names = ["table_name", "column_name"]
-
+
def relbind(self, db, atts):
rels = db.rels
pairs = []
@@ -164,15 +164,15 @@
pairs.append( (relname, att) )
self.pairs = pairs
return self
-
+
def listing(self):
return self.pairs
-
+
class IndexAttsView(ColumnsView):
"""indices and attributes."""
-
+
column_names = ["index_name", "column_name"]
-
+
def relbind(self, db, atts):
indices = db.indices
pairs = []
@@ -181,4 +181,3 @@
pairs.append( (iname, att) )
self.pairs = pairs
return self
-
=== Zope3/src/zope/app/rdb/gadfly/gfserve.py 1.1.2.3 => 1.1.2.4 ===
--- Zope3/src/zope/app/rdb/gadfly/gfserve.py:1.1.2.3 Tue Dec 24 13:04:46 2002
+++ Zope3/src/zope/app/rdb/gadfly/gfserve.py Tue Dec 24 21:20:43 2002
@@ -1,7 +1,7 @@
"""gadfly server mode
- script usage
-
+ script usage
+
python gfserve.py port database directory password [startup]
test example
@@ -15,14 +15,14 @@
startup if present should be the name of a module to use
for startup. The Startup module must contain a function
-
+
Dict = startup(admin_policy, connection, Server_instance)
-
+
which performs any startup actions on the database needed
and returns either None or a Dictionary of
-
+
name > policy objects
-
+
where the policy objects describe policies beyond the
admin policy. The startup function may also
modify the admin_policy (disabling queries for example).
@@ -56,7 +56,7 @@
'''
in this case 'updatenorm' requires 2 dynamic parameters when
invoked from a client.
-
+
Script stdout lists server logging information.
Some server administration services (eg shutdown)
@@ -136,17 +136,17 @@
# autocommit.
EXECUTE_STATEMENT = "EXECUTE_STATEMENT"
-ACTIONS = [SHUTDOWN, RESTART, CHECKPOINT,
+ACTIONS = [SHUTDOWN, RESTART, CHECKPOINT,
EXECUTE_PREPARED, EXECUTE_STATEMENT]
-
+
class Server:
"""database server: listen for commands"""
-
+
verbose = 1
-
+
# wait X minutes on each server loop
select_timeout = 60*5
-
+
# do a checkpoint each X times thru server loop
check_loop = 5
@@ -230,10 +230,10 @@
continue
else:
try:
- reader.poll()
+ reader.poll()
finally:
- pass # AFTER DEBUG CHANGE THIS!
- # in blocking mode, service ready request,
+ pass # AFTER DEBUG CHANGE THIS!
+ # in blocking mode, service ready request,
# commit on no error
for conn in pending_connects.keys():
reader = pending_connects[conn]
@@ -253,7 +253,7 @@
if not policies.has_key(actor_name):
if verbose:
print "no such policy: "+actor_name
- reply_exception(NameError,
+ reply_exception(NameError,
"no such policy: "+actor_name, conn)
policy = None
else:
@@ -309,11 +309,11 @@
self.startup_load()
# get socket last in case of failure earlier
self.getsocket()
-
+
HOST = ""
BACKLOG = 5
-
+
def getsocket(self):
"""get the listening socket"""
verbose = self.verbose
@@ -326,17 +326,17 @@
print "trying to set REUSEADDR",\
sock.getsockopt(socket.SOL_SOCKET,
socket.SO_REUSEADDR)
- sock.setsockopt(socket.SOL_SOCKET,
+ sock.setsockopt(socket.SOL_SOCKET,
socket.SO_REUSEADDR, 1)
- except:
- if verbose:
- print "set of REUSEADDR failed", sys.exc_type, sys.exc_value
+ except:
+ if verbose:
+ print "set of REUSEADDR failed", sys.exc_type, sys.exc_value
pass
sock.bind((self.HOST, self.port))
sock.listen(self.BACKLOG)
self.socket = sock
return sock
-
+
def getconnection(self):
"""get the db connection"""
from gadfly import gadfly
@@ -355,7 +355,7 @@
if test is not None:
self.policies = test
self.policies["admin"] = admin_policy
-
+
def get_admin_policy(self):
"""return the admin policy for priviledged access."""
p = self.admin_policy = Policy(
@@ -366,25 +366,25 @@
"""security policy"""
verbose = 0
-
+
# allow arbitrary sql statments
general_queries = 0
-
+
# dictionary of named accesses as strings
named_accesses = None
-
+
# dictionary of prepared named accesses
prepared_cursors = None
-
+
def __init__(self, name, password, connection, queries=0):
"""create a policy (name, password, connection)
-
+
name is the name of the policy
password is the access policy (None for no password)
connection is the database connection.
set queries to allow general accesses (unrestricted)
"""
- if self.verbose:
+ if self.verbose:
print "policy.__init__", name
self.general_queries = queries
self.name = name
@@ -393,15 +393,15 @@
self.socket = None
self.named_accesses = {}
self.prepared_cursors = {}
-
+
def __setitem__(self, name, value):
if self.verbose:
print "policy", self.name, ":", (name, value)
from types import StringType
if type(name) is not StringType or type(value) is not StringType:
- raise ValueError, "cursor names and contents must be strings"
+ raise ValueError, "cursor names and contents must be strings"
self.named_accesses[name] = value
-
+
def execute_named(self, name, params=None):
"""execute a named (prepared) sql statement"""
if self.verbose:
@@ -419,7 +419,7 @@
# prepare a new cursor
pc[name] = cursor = con.cursor()
return self.execute(cursor, stat, params)
-
+
def execute(self, cursor, statement, params=None):
"""execute a statement in a cursor"""
if self.verbose:
@@ -434,7 +434,7 @@
except:
result = None
return result
-
+
def execute_any_statement(self, statement, params=None):
"""execute any statement."""
if self.verbose:
@@ -442,7 +442,7 @@
con = self.connection
cursor = con.cursor()
return self.execute(cursor, statement, params)
-
+
def action(self, certificate, datastring, socket):
"""perform a database/server action after checking certificate"""
verbose = self.verbose
@@ -476,54 +476,54 @@
exceptiondata = "%s\n%s" %(sys.exc_type,
str(sys.exc_value))
if verbose:
- from traceback import print_tb
- print_tb(tb)
- self.reply_exception(ServerError,
+ from traceback import print_tb
+ print_tb(tb)
+ self.reply_exception(ServerError,
"unexpected exception: "+exceptiondata, socket)
raise ServerError, exceptiondata
else:
raise ServerError, "unknown action: "+`action`
-
+
def certify(self, datastring, certificate, password):
# hook for subclassing
return certify(datastring, certificate, password)
-
+
def policy_SHUTDOWN(self, socket):
self.reply_success("attempting server shutdown", socket)
raise SHUTDOWN, "please shut down the server"
-
+
def policy_RESTART(self, socket):
self.reply_success("attempting server restart", socket)
raise RESTART, "please restart the server"
-
+
def policy_CHECKPOINT(self, socket):
self.reply_success("attempting server checkpoint", socket)
raise CHECKPOINT, "please checkpoint the server"
-
+
def policy_EXECUTE_PREPARED(self, name, dyn, socket):
try:
result = self.execute_named(name, dyn)
self.reply_success(result, socket)
except PreparedNameError, detail:
- self.reply_exception(PreparedNameError,
+ self.reply_exception(PreparedNameError,
"no such prepared statement: "+name,
socket)
-
+
def policy_EXECUTE_STATEMENT(self, stat, dyn, socket):
if not self.general_queries:
- self.reply_exception(ServerError,
+ self.reply_exception(ServerError,
"general statements disallowed on this policy",
socket)
raise ServerError, "illegal statement attempt for: "+self.name
result = self.execute_any_statement(stat, dyn)
self.reply_success(result, socket)
-
+
def reply_exception(self, exc, info, socket):
# hook for subclassing
reply_exception(exc, info, socket)
-
+
def reply_success(self, data, socket):
# hook for subclassing
reply_success(data, socket)
-
+
if __name__=="__main__": main()
=== Zope3/src/zope/app/rdb/gadfly/gfsocket.py 1.1.2.3 => 1.1.2.4 ===
--- Zope3/src/zope/app/rdb/gadfly/gfsocket.py:1.1.2.3 Tue Dec 24 13:04:46 2002
+++ Zope3/src/zope/app/rdb/gadfly/gfsocket.py Tue Dec 24 21:20:43 2002
@@ -8,7 +8,7 @@
SUCCESS = "SUCCESS"
EXCEPTION = "EXCEPTION"
-
+
def reply_exception(exception, info, socket):
"""send an exception back to the client"""
# any error is invisible to client
@@ -20,27 +20,27 @@
#info = "%s %s" % (sys.exc_type, sys.exc_value)
socket.close()
#raise ServerError, "reply_exception failed: "+`info`
-
+
def reply_success(data, socket):
"""report success with data back to client"""
reply( (SUCCESS, data), socket)
-
+
def reply(data, socket):
from marshal import dumps
marshaldata = dumps(data)
send_packet(socket, marshaldata)
socket.close()
-
+
def send_packet(socket, data):
"""blast out a length marked packet"""
send_len(data, socket)
socket.send(data)
-
+
def send_len(data, socket):
"""send length of data as cr terminated int rep"""
info = `len(data)`+"\n"
socket.send(info)
-
+
def send_certified_action(actor_name, action, arguments, password, socket):
from marshal import dumps
marshaldata = dumps( (action, arguments) )
@@ -48,13 +48,13 @@
#print actor_name, cert, marshaldata
marshaldata = dumps( (actor_name, cert, marshaldata) )
send_packet(socket, marshaldata)
-
+
def unpack_certified_data(data):
from marshal import loads
# sanity check
unpack = (actor_name, certificate, marshaldata) = loads(data)
return unpack
-
+
def recv_data(socket, timeout=10):
"""receive data or time out"""
from time import time
@@ -73,7 +73,7 @@
reader.poll()
done = (reader.mode==READY)
return reader.data
-
+
def interpret_response(data):
"""interpret response data, raise exception if needed"""
from marshal import loads
@@ -85,7 +85,7 @@
raise EXCEPTION, data
else:
raise ValueError, "unknown indicator: "+`indicator`
-
+
# packet reader modes
LEN = "LEN"
DATA = "DATA"
@@ -95,16 +95,16 @@
BLOCK_SIZE = 4028
LEN_LIMIT = BLOCK_SIZE * 10
-
+
class Packet_Reader:
"""nonblocking pseudo-packet reader."""
-
+
# packets come in as decimal_len\ndata
# (note: cr! not crlf)
-
+
# kick too large requests if set
limit_len = LEN_LIMIT
-
+
def __init__(self, socket):
self.socket = socket
self.length = None
@@ -114,17 +114,17 @@
self.received = ""
self.data = None
self.mode = LEN
-
+
def __len__(self):
if self.mode is LEN:
raise ValueError, "still reading length"
return self.length
-
+
def get_data(self):
if self.mode is not READY:
raise ValueError, "still reading"
return self.data
-
+
def poll(self):
mode = self.mode
if mode is READY:
@@ -143,7 +143,7 @@
# note: do not fall thru automatically
elif mode is DATA:
self.read_data()
-
+
def read_len(self):
"""assume socket is readable now, read length"""
socket = self.socket
@@ -217,8 +217,7 @@
raise ValueError, "cannot generate certificate for empty string"
taggedstring = password + String
return new(taggedstring).digest()
-
+
def certify(String, cert, password):
"""check a certificate for a string"""
return certificate(String, password) == cert
-
=== Zope3/src/zope/app/rdb/gadfly/gfstest.py 1.1.2.3 => 1.1.2.4 ===
--- Zope3/src/zope/app/rdb/gadfly/gfstest.py:1.1.2.3 Tue Dec 24 13:04:46 2002
+++ Zope3/src/zope/app/rdb/gadfly/gfstest.py Tue Dec 24 21:20:43 2002
@@ -8,7 +8,7 @@
python gfstest.py start
THIS WILL ONLY WORK IF YOU CREATED THE test DATABASE IN
- DIRECTORY dbtest FIRST USING
+ DIRECTORY dbtest FIRST USING
python gftest.py dbtest
@@ -164,9 +164,9 @@
v = sys.exc_value
from types import TupleType, ListType
if type(v) in (TupleType, ListType):
- for x in v: print x
+ for x in v: print x
else:
- print v
+ print v
else:
print "executed"
#print q
@@ -199,7 +199,7 @@
cursor.execute(stat, ("cheers",))
for x in cursor.fetchall():
print x
-
+
admin_queries = [
"""select count(*) from work""",
"""select * from frequents""",
=== Zope3/src/zope/app/rdb/gadfly/gftest.py 1.1.2.3 => 1.1.2.4 ===
--- Zope3/src/zope/app/rdb/gadfly/gftest.py:1.1.2.3 Tue Dec 24 13:04:46 2002
+++ Zope3/src/zope/app/rdb/gadfly/gftest.py Tue Dec 24 21:20:43 2002
@@ -93,10 +93,10 @@
D = [
("index.html", 1, 2100),
("index.html", 2, 3300),
- ("index.html", 3, 1950),
- ("products.html", 1, 15),
- ("products.html", 2, 650),
- ("products.html", 3, 98),
+ ("index.html", 3, 1950),
+ ("products.html", 1, 15),
+ ("products.html", 2, 650),
+ ("products.html", 3, 98),
("people.html", 1, 439),
("people.html", 2, 12),
("people.html", 3, 665),
@@ -106,18 +106,18 @@
for (table, stuff) in dpairs:
ins = "insert into %s values (?, ?, ?)" % table
if table!="frequents":
- for parameters in dataseq(stuff):
- print "singleinsert", table, parameters
- curs.execute(ins, parameters)
+ for parameters in dataseq(stuff):
+ print "singleinsert", table, parameters
+ curs.execute(ins, parameters)
else:
- print
- print "multiinsert", table
- parameters = dataseq(stuff)
- for p in parameters:
- print p
- print "multiinsert..."
- curs.execute(ins, parameters)
- print;print
+ print
+ print "multiinsert", table
+ parameters = dataseq(stuff)
+ for p in parameters:
+ print p
+ print "multiinsert..."
+ curs.execute(ins, parameters)
+ print;print
print
print "INDICES"
for ci in indices:
@@ -130,7 +130,7 @@
print x
curs.execute(x)
print curs.pp()
-
+
statement = """select name, hours
from work"""
curs.execute(statement)
@@ -150,11 +150,11 @@
# print x
all = curs.fetchall()
if not all:
- print "empty!"
+ print "empty!"
else:
- print curs.pp()
- #for t in all:
- #print t
+ print curs.pp()
+ #for t in all:
+ #print t
#return
print
print "DYNAMIC QUERIES"
@@ -167,10 +167,10 @@
# print x
all = curs.fetchall()
if not all:
- print "empty!"
+ print "empty!"
else:
- for t in all:
- print t
+ for t in all:
+ print t
print "repeat test"
from time import time
for x in repeats:
@@ -189,7 +189,7 @@
connect.close()
print; print
return connect
-
+
table_creates = [
"create table frequents (drinker varchar, bar varchar, perweek integer)",
"create table likes (drinker varchar, beer varchar, perday integer)",
@@ -200,46 +200,46 @@
where drinker not in
(select drinker from likes)""",
]
-
+
fdata = """\
- adam lolas 1
- woody cheers 5
- sam cheers 5
- norm cheers 3
- wilt joes 2
- norm joes 1
- lola lolas 6
- norm lolas 2
- woody lolas 1
- pierre frankies 0"""
-
+ adam lolas 1
+ woody cheers 5
+ sam cheers 5
+ norm cheers 3
+ wilt joes 2
+ norm joes 1
+ lola lolas 6
+ norm lolas 2
+ woody lolas 1
+ pierre frankies 0"""
+
sdata = """\
- cheers bud 500
- cheers samaddams 255
- joes bud 217
- joes samaddams 13
- joes mickies 2222
- lolas mickies 1515
- lolas pabst 333
- winkos rollingrock 432
- frankies snafu 5"""
-
+ cheers bud 500
+ cheers samaddams 255
+ joes bud 217
+ joes samaddams 13
+ joes mickies 2222
+ lolas mickies 1515
+ lolas pabst 333
+ winkos rollingrock 432
+ frankies snafu 5"""
+
ldata = """\
- adam bud 2
- wilt rollingrock 1
- sam bud 2
- norm rollingrock 3
- norm bud 2
- nan sierranevada 1
- woody pabst 2
- lola mickies 5"""
-
+ adam bud 2
+ wilt rollingrock 1
+ sam bud 2
+ norm rollingrock 3
+ norm bud 2
+ nan sierranevada 1
+ woody pabst 2
+ lola mickies 5"""
+
dpairs = [
("frequents", fdata),
("serves", sdata),
("likes", ldata),
]
-
+
def dataseq(s):
from string import split
l = split(s, "\n")
@@ -249,7 +249,7 @@
l[2] = atoi(l[2])
result = map(tuple, result)
return result
-
+
indices = [
"""create index fd on frequents (drinker)""",
"""create index sbb on serves (beer, bar)""",
@@ -334,7 +334,7 @@
from accesses
order by month, hits desc""",
]
-
+
queries = [
"""select * from nondrinkers""",
"""select drinker as x from likes
@@ -360,18 +360,18 @@
where beer not in (select beer from serves)
order by 3 desc""",
"""select avg(perweek) from frequents""",
-"""select *
+"""select *
from frequents
where perweek <= (select avg(perweek) from frequents)""",
-"""select *
+"""select *
from serves""",
"""select bar, avg(quantity)
from serves
group by bar""",
-"""select *
+"""select *
from serves s1
- where quantity <= (select avg(quantity)
- from serves s2
+ where quantity <= (select avg(quantity)
+ from serves s2
where s1.bar=s2.bar)""",
"""select * from frequents
where perweek > (select avg(perweek) from frequents)""",
@@ -386,11 +386,11 @@
"""select * from frequents
where perweek <= all (select perweek from frequents)""",
"""select * from frequents f1
- where perweek < any
+ where perweek < any
(select perweek from frequents f2
where f1.drinker = f2.drinker)""",
"""select * from frequents f1
- where perweek = all
+ where perweek = all
(select perweek from frequents f2
where f1.drinker = f2.drinker)""",
"""select * from frequents f1
@@ -420,7 +420,7 @@
# where f1.drinker<>f2.drinker and f1.bar=f2.bar)""",
"""select *
from frequents
- where perweek between 2 and
+ where perweek between 2 and
(select avg(perweek) from frequents)""",
"""select *
from frequents
@@ -491,7 +491,7 @@
"""select sum(quantity), avg(quantity), count(*), sum(quantity)/count(quantity)
from serves""",
"""select beer, sum(quantity), avg(quantity), count(*), sum(quantity)/count(quantity)
- from serves
+ from serves
group by beer""",
"""select sum(quantity), avg(quantity), count(*), sum(quantity)/count(quantity)
from serves
@@ -525,7 +525,7 @@
]
dynamic_queries = [
-( "select bar from frequents where drinker=?", ("norm",) ),
+( "select bar from frequents where drinker=?", ("norm",) ),
( "select * from frequents where drinker=? or bar=?", ("norm", "cheers") )
]
@@ -558,18 +558,18 @@
"""drop index tdindex""",
"""delete from templikes
where dr=(select min(dr) from templikes)""",
-"""insert into templikes (dr, be)
+"""insert into templikes (dr, be)
select max(dr), min(be) from templikes""",
"""select * from templikes""",
"""select * from frequents""",
-"""update frequents
- set perweek=(select max(perweek)
+"""update frequents
+ set perweek=(select max(perweek)
from frequents
where drinker='norm')
where drinker='woody'""",
"""select * from frequents""",
"""create view lazy as
- select drinker, sum(perweek) as wasted
+ select drinker, sum(perweek) as wasted
from frequents
group by drinker
having sum(perweek)>4
@@ -670,7 +670,7 @@
postresults = []
for s in rollback_queries:
print s
- try:
+ try:
cursor.execute(s)
postresults.append(cursor.fetchall())
print cursor.pp()
@@ -687,8 +687,8 @@
connect.dumplog()
print "*** RESTARTING (RECOVER FROM LOG, DISCARD UNCOMMITTED)"
connect.restart()
-
-def retest(directory):
+
+def retest(directory):
print "*" * 30
print "*** reconnect test"
from gadfly import gadfly
@@ -709,15 +709,15 @@
#connect.DUMP_ALL()
connect.close()
return connect
-
+
if __name__=="__main__":
- import sys
- argv = sys.argv
- if len(argv)<2:
- print "USAGE: python <thismodule> <db_directory>"
- print " please provide a directory for test database!"
- else:
- directory = argv[1]
- test(directory)
- rollbacktest(directory)
- retest(directory)
+ import sys
+ argv = sys.argv
+ if len(argv)<2:
+ print "USAGE: python <thismodule> <db_directory>"
+ print " please provide a directory for test database!"
+ else:
+ directory = argv[1]
+ test(directory)
+ rollbacktest(directory)
+ retest(directory)
=== Zope3/src/zope/app/rdb/gadfly/idl.py 1.1.2.3 => 1.1.2.4 ===
--- Zope3/src/zope/app/rdb/gadfly/idl.py:1.1.2.3 Tue Dec 24 13:04:46 2002
+++ Zope3/src/zope/app/rdb/gadfly/idl.py Tue Dec 24 21:20:43 2002
@@ -44,8 +44,8 @@
## 7 puncts []
@R r7 :: interface_header >> interface identifier [ inheritance_spec ]
-## 8
-@R r8a :: interface_body >>
+## 8
+@R r8a :: interface_body >>
@R r8b :: interface_body >> export interface_body
## 9
@@ -132,7 +132,7 @@
@R r25a :: boolean_literal >> TRUE
@R r25b :: boolean_literal >> FALSE
-##26
+##26
@R r26 :: positive_int_literal >> const_expr
##27 kw typedef
@@ -188,7 +188,7 @@
@R r38a :: floating_pt_type >> float
@R r38b :: floating_pt_type >> double
-##39
+##39
@R r39a :: integer_type >> signed_int
@R r39b :: integer_type >> unsigned_int
@@ -209,7 +209,7 @@
##44 kw unsigned
@R r44 :: unsigned_long_int >> unsigned long
-##45
+##45
@R r45 :: unsigned_short_int >> unsigned short
##46 kw char
@@ -235,7 +235,7 @@
@R r52 :: member >> type_spec declarators ;
##53 kw union switch
-@R r53 :: union_type >>
+@R r53 :: union_type >>
union identifier switch ( switch_type_spec ) { switch_body }
##54
@@ -256,7 +256,7 @@
##57 kw default case
-@R r57a :: case_label >> case const_expr :
+@R r57a :: case_label >> case const_expr :
@R r57b :: case_label >> default :
##58
@@ -298,10 +298,10 @@
@R r66c :: members >> member_list
##67
-@R r67a :: op_dcl >>
+@R r67a :: op_dcl >>
maybe_op_attribute op_type_spec identifier parameter_dcls
maybe_raises_expr maybe_context_expr
-@R r67b :: maybe_op_attribute >>
+@R r67b :: maybe_op_attribute >>
@R r67c :: maybe_op_attribute >> op_attribute
@R r67d :: maybe_raises_expr >>
@R r67e :: maybe_raises_expr >> raises_expr
@@ -357,7 +357,7 @@
member_list member
signed_int unsigned_int signed_long_int signed_short_int
simple_declarator complex_declarator array_declarator
-declarator
+declarator
sequence_type string_type
floating_pt_type integer_type char_type boolean_type
octet_type any_type
@@ -384,7 +384,7 @@
interface module const TRUE FALSE typedef float double long
unsigned short char boolean octet any struct union switch
enum string attribute readonly default case sequence ::
-"""
+"""
# NOTE: FOR NECESSARY HACKERY REASONS :: IS A KEYWORD!
punctuations = ";{}()[],:|^&<>+-*/%~="
@@ -414,18 +414,18 @@
## (not possible using standard kjParsing, requires a special override)
import kjParser
class myLexDictionary(kjParser.LexDictionary):
- def __init__(self):
- kjParser.LexDictionary.__init__(self)
- map = ((kjParser.KEYFLAG, "coloncolon"), "coloncolon")
- self.keywordmap["::"] = map
- self.keywordmap["coloncolon"] = map
-
- def Token(self, String, StartPosition):
- if String[StartPosition:StartPosition+2] == "::":
- tok = self.keywordmap["::"]
- return (tok, 2)
- # default:
- return kjParseBuild.LexDictionary.Token(self, String, StartPosition)
+ def __init__(self):
+ kjParser.LexDictionary.__init__(self)
+ map = ((kjParser.KEYFLAG, "coloncolon"), "coloncolon")
+ self.keywordmap["::"] = map
+ self.keywordmap["coloncolon"] = map
+
+ def Token(self, String, StartPosition):
+ if String[StartPosition:StartPosition+2] == "::":
+ tok = self.keywordmap["::"]
+ return (tok, 2)
+ # default:
+ return kjParseBuild.LexDictionary.Token(self, String, StartPosition)
# default bind all rules
@@ -444,4 +444,4 @@
idl.Compile()
return idl
-if __name__=="__main__": GrammarBuild()
\ No newline at end of file
+if __name__=="__main__": GrammarBuild()
=== Zope3/src/zope/app/rdb/gadfly/kjParseBuild.py 1.1.2.1 => 1.1.2.2 === (2336/2436 lines abridged)
--- Zope3/src/zope/app/rdb/gadfly/kjParseBuild.py:1.1.2.1 Tue Dec 24 13:04:46 2002
+++ Zope3/src/zope/app/rdb/gadfly/kjParseBuild.py Tue Dec 24 21:20:43 2002
@@ -41,119 +41,119 @@
#
class CFSMachine(kjParser.FSMachine):
- def __init__(self, nonterm):
- kjParser.FSMachine.__init__(self, nonterm)
+ def __init__(self, nonterm):
+ kjParser.FSMachine.__init__(self, nonterm)
- # return the epsilon closure of the FSM as a new FSM
- #
- # DoNullMap, if set, will map unexpected tokens to
- # the "empty" state (usually creating a really big fsm)
- #
- def Eclosure(self, Epsilon, DoNullMaps=0):
- Closure = CFSMachine( self.root_nonTerminal )
-
- # compute the Epsilon Graph between states
- EGraph = kjSet.NewDG([])
- for State in range(0,self.maxState+1):
- # every state is E-connected to self
- kjSet.AddArc( EGraph, State, State )
- # add possible transition on epsilon (ONLY ONE SUPPORTED!)
- key = (State, Epsilon)
- if self.StateTokenMap.has_key(key):
- keymap = self.StateTokenMap[key]
- if keymap[0][0] != MOVETOFLAG:
- raise TypeError, "unexpected map type in StateTokenMap"
- for (Flag,ToState) in keymap:
- kjSet.AddArc( EGraph, State, ToState )
- #endfor
- # transitively close EGraph
- kjSet.TransClose( EGraph )
-
- # Translate EGraph into a dictionary of lists
- EMap = {}
- for State in range(0,self.maxState+1):
- EMap[State] = kjSet.Neighbors( EGraph, State )
-
- # make each e-closure of each self.state a state of the closure FSM.
- # here closure states assumed transient -- reset elsewhere.
- # first do the initial state
- Closure.States[ Closure.initial_state ] = \
- [TRANSFLAG, kjSet.NewSet(EMap[self.initial_state]) ]
- # do all other states (save initial and successful final states)
- #for State in range(0,self.maxState+1):
- # if State != self.initial_state \
- # and State != self.successful_final_state:
[-=- -=- -=- 2336 lines omitted -=- -=- -=-]
+ RX = kjParser.ParseRule( X, [ oppar, Y, clpar ] )
+ RY = kjParser.ParseRule( Y, [] )
+ rl2 = [RX,RY]
+ rs2 = ruleset(X, rl2)
+ rs2.CompFirst()
+ rs2.CompFollow()
+ rs2.CompSLRNFA()
+ rs2.CompDFA()
+ rs2.SLRFixDFA()
+ DFA2 = rs2.DFA
+
+ ttt2 = dummy()
+ def TESTDFA2( STRING, DOREDUCTIONS = 1):
+ return TESTDFA( STRING, ttt2, DFA2, rl2, DOREDUCTIONS )
+
+ # the following grammar should fail to be slr
+ # (Aho,Ullman p. 213)
+
+ S = kjParser.nonterminal("S")
+ L = kjParser.nonterminal("L")
+ R = kjParser.nonterminal("R")
+ RS1 = kjParser.ParseRule( S, [L, equals, R] )
+ RS2 = kjParser.ParseRule( S, [R], echo )
+ RL1 = kjParser.ParseRule( L, [star, R])
+ RL2 = kjParser.ParseRule( L, [id])
+ RR1 = kjParser.ParseRule( R, [L] )
+ rs3 = ruleset(S, [RS1,RS2,RL1,RL2,RR1])
+ rs3.CompFirst()
+ rs3.CompFollow()
+ rs3.CompSLRNFA()
+ rs3.CompDFA()
+ #rs3.SLRFixDFA() # should fail and does.
+
+ # testing RULEGRAM
+ ObjG = NullCGrammar()
+ ObjG.Addterm("id","id",echo)
+ ObjG.Nonterms("T E Ep F Tp")
+ ObjG.Keywords("begin end")
+ ObjG.punct("+*()")
+ ObjG.comments(["--.*\n"])
+ # PROBLEM WITH COMMENTS???
+ Rulestr = """
+ ## what a silly grammar!
+ T ::
+ @R One :: T >> begin E end
+ @R Three :: E >>
+ @R Two :: E >> E + T
+ @R Four :: E >> ( T )
+ """
+ RL = RULEGRAM.DoParse1( Rulestr, ObjG )
=== Zope3/src/zope/app/rdb/gadfly/kjParser.py 1.1.2.1 => 1.1.2.2 === (1967/2067 lines abridged)
--- Zope3/src/zope/app/rdb/gadfly/kjParser.py:1.1.2.1 Tue Dec 24 13:04:46 2002
+++ Zope3/src/zope/app/rdb/gadfly/kjParser.py Tue Dec 24 21:20:43 2002
@@ -125,7 +125,7 @@
#
# LD[string] # retrieval!
# returns ((KEYFLAG, Keywordstring), Keywordstring)
-# if the (entire) string matches a keyword or a
+# if the (entire) string matches a keyword or a
# punctuation Keywordstring.
# otherwise returns ((TERMFLAG, Terminalname), value)
# if the (entire) string matches the regular expression for
@@ -147,314 +147,314 @@
#
class LexDictionary:
- def __init__(self):
+ def __init__(self):
# commentpatterns is simply a list of compiled regular expressions
# that represent comments
- self.commentpatterns = []
- # commentstrings is used for debugging/dumping/reconstruction etc.
- self.commentstrings = []
- # punctuationlist is a string of punctuations
- self.punctuationlist = ""
- # keywordmap is a dictionary mapping recognized keyword strings
- # and punctuations to their constant representations.
- self.keywordmap = KeywordDict()
- # regexprlist is a list of triples (regex,Flag,function) mapping
- # regular expressions to their flag and interpreter function.
- self.regexprlist = []
-
- def Dump(self):
- print "comments = ", self.commentstrings
- print "punctuations = ", self.punctuationlist
- print "keywordmap ="
- self.keywordmap.Dump()
- print "regexprlist =", self.regexprlist
-
- def __getitem__(self,key):
- # try to match string to a keyword
- try:
- return self.keywordmap[key]
- except KeyError:
- # try to match a regular expression
- found = 0 # so far not found
- length = len(key)
- for triple in self.regexprlist:
- (regexpr, Flag, Function) = triple
- index = RMATCH(regexpr,key)
- if index == length:
[-=- -=- -=- 1967 lines omitted -=- -=- -=-]
+ (kind,name) = tokens[tokenindex]
+ if kind == KEYFLAG:
+ tokens[tokenindex] = LexD.keyword(name)
+ elif not kind in [TERMFLAG, NONTERMFLAG]:
+ raise FlowError, "unknown token type"
+ # not needed
+ self.tokens = tokens
+
+ def MakeRules(self):
+ Grammar = self.Gram
+ Grammar.DFA.root_nonTerminal = self.Root
+ NameIndex = Grammar.RuleNameToIndex
+ RuleTuples = self.RuleTups
+ nRules = len(RuleTuples)
+ RuleList = [None] * nRules
+ for index in range(nRules):
+ (Name, Components) = RuleTuples[index]
+ rule = apply(ParseRule, Components)
+ rule.Name = Name
+ RuleList[index] = rule
+ NameIndex[Name] = index
+ Grammar.RuleL = RuleList
+
+ def MakeTransitions(self):
+ Grammar = self.Gram
+ DFA = Grammar.DFA
+ StateTokenMap = DFA.StateTokenMap
+ tokens = self.tokens
+ # record the state number
+ DFA.maxState = self.MaxStates
+ # this is historical, unfortunately... CLEAN IT UP SOMEDAY!
+ # THE DFA.States DICT IS NOT NEEDED (?) (here)
+ for state in range(1, self.MaxStates+1):
+ DFA.States[state] = [TRANSFLAG]
+ # record the reductions
+ for (fromState, TokenIndex, rulenum) in self.reducts:
+ DFA.SetReduction(fromState, tokens[TokenIndex], rulenum)
+ # record the transitions
+ for (fromState, TokenIndex, ToState) in self.moveTos:
+ DFA.SetMap(fromState, tokens[TokenIndex], ToState)
+
+ def Cleanup(self):
+ Grammar = self.Gram
+ Grammar.CleanUp()
################# FOLLOWING CODE IS FOR REGRESSION TESTING ONLY
################# DELETE IT IF YOU WANT/NEED
#### All tests for this module deleted, since
-#### ParseBuild module tests are sufficient.
+#### ParseBuild module tests are sufficient.
=== Zope3/src/zope/app/rdb/gadfly/kjSet.py 1.1.2.1 => 1.1.2.2 ===
--- Zope3/src/zope/app/rdb/gadfly/kjSet.py:1.1.2.1 Tue Dec 24 13:04:46 2002
+++ Zope3/src/zope/app/rdb/gadfly/kjSet.py Tue Dec 24 21:20:43 2002
@@ -15,9 +15,9 @@
def Empty(Set):
if Set == {}:
- return 1
+ return 1
else:
- return 0
+ return 0
def get_elts(Set):
return Set.keys()
@@ -31,16 +31,16 @@
def addMember(Elt,Set):
change = 0
if not Set.has_key(Elt):
- Set[Elt] = 1
- change = 1
+ Set[Elt] = 1
+ change = 1
return change
def Augment(Set, OtherSet):
change = 0
for Elt in OtherSet.keys():
if not Set.has_key(Elt):
- Set[Elt] = 1
- change = 1
+ Set[Elt] = 1
+ change = 1
return change
@@ -48,8 +48,8 @@
change = 0
for Elt in OtherSet.keys():
if Set.has_key(Elt):
- del Set[Elt]
- change = 1
+ del Set[Elt]
+ change = 1
return change
# side effect free functions
@@ -58,14 +58,14 @@
Result = {}
for Elt in Set1.keys():
if Set2.has_key(Elt):
- Result[Elt] = 1
+ Result[Elt] = 1
return Result
def Difference(Set1, Set2):
Result = {}
for Elt in Set1.keys():
if not Set2.has_key(Elt):
- Result[Elt] = 1
+ Result[Elt] = 1
return Result
def Union(Set1,Set2):
@@ -78,15 +78,15 @@
Result = 1
for Elt in Set1.keys():
if not Set2.has_key(Elt):
- Result = 0
- return Result # nonlocal
+ Result = 0
+ return Result # nonlocal
return Result
def Same(Set1,Set2):
if Subset(Set1,Set2) and Subset(Set2,Set1):
- return 1
+ return 1
else:
- return 0
+ return 0
# directed graphs as Dictionaries of Sets
# also only works for immutable nodes
@@ -112,25 +112,25 @@
def AddArc(Graph, Source, Dest):
change = 0
if Graph.has_key(Source):
- Adjacent = Graph[Source]
- if not member(Dest,Adjacent):
- addMember(Dest,Adjacent)
- change = 1
+ Adjacent = Graph[Source]
+ if not member(Dest,Adjacent):
+ addMember(Dest,Adjacent)
+ change = 1
else:
- Graph[Source] = NewSet( [ Dest ] )
- change = 1
+ Graph[Source] = NewSet( [ Dest ] )
+ change = 1
return change
def Neighbors(Graph,Source):
if Graph.has_key(Source):
- return get_elts(Graph[Source])
+ return get_elts(Graph[Source])
else:
- return []
+ return []
def HasArc(Graph, Source, Dest):
result = 0
if Graph.has_key(Source) and member(Dest, Graph[Source]):
- result = 1
+ result = 1
return result
def Sources(Graph):
@@ -151,8 +151,8 @@
for Middle in Neighbors(G2,G2Source):
for G3Dest in Neighbors(G3, Middle):
if not HasArc(G1, G2Source, G3Dest):
- change = 1
- AddArc(G1, G2Source, G3Dest)
+ change = 1
+ AddArc(G1, G2Source, G3Dest)
return change
# in place transitive closure of a graph
@@ -160,9 +160,9 @@
change = AddComposition(Graph, Graph, Graph)
somechange = change
while change:
- change = AddComposition(Graph, Graph, Graph)
- if not somechange:
- somechange = change
+ change = AddComposition(Graph, Graph, Graph)
+ if not somechange:
+ somechange = change
return somechange
########### SQueue stuff
@@ -194,24 +194,24 @@
oldlen = len(B)
# look for an available position
while B[cursor] != None:
- cursor = cursor+1
- if cursor >= oldlen: cursor = START
- if cursor == B[NEW]: #back to beginning
- break
+ cursor = cursor+1
+ if cursor >= oldlen: cursor = START
+ if cursor == B[NEW]: #back to beginning
+ break
# resize if wrapped
if B[cursor] != None:
- B = B + [None] * oldlen
- cursor = oldlen
- B[OLD] = START
+ B = B + [None] * oldlen
+ cursor = oldlen
+ B[OLD] = START
if B[cursor] != None:
- raise IndexError, "can't insert?"
+ raise IndexError, "can't insert?"
# add the elt
B[cursor] = (elt,)
B[NEW] = cursor
# B nonempty so OLD and NEW should differ.
if B[OLD] == cursor:
- B[NEW] = cursor + 1
- if B[NEW]<=len(B): B[NEW] = START
+ B[NEW] = cursor + 1
+ if B[NEW]<=len(B): B[NEW] = START
return B
def BGgetdel(B):
@@ -219,18 +219,18 @@
cursor = B[OLD]
blen = len(B)
while B[cursor]==None:
- cursor = cursor+1
- if cursor>=blen: cursor = START
- if cursor == B[OLD]: break # wrapped
+ cursor = cursor+1
+ if cursor>=blen: cursor = START
+ if cursor == B[OLD]: break # wrapped
if B[cursor] == None:
- raise IndexError, "delete from empty grabbag(?)"
+ raise IndexError, "delete from empty grabbag(?)"
# test to see if bag is empty (position cursor2 at nonempty slot)
cursor2 = cursor+1
if cursor2>=blen: cursor2 = START
while B[cursor2]==None:
- cursor2 = cursor2+1
- if cursor2>=blen: cursor2 = START
- # since B[cursor] not yet deleted while will terminate
+ cursor2 = cursor2+1
+ if cursor2>=blen: cursor2 = START
+ # since B[cursor] not yet deleted while will terminate
# get and delete the elt
(result,) = B[cursor]
B[cursor] = None
=== Zope3/src/zope/app/rdb/gadfly/kjbuckets0.py 1.1.2.3 => 1.1.2.4 === (1838/1938 lines abridged)
--- Zope3/src/zope/app/rdb/gadfly/kjbuckets0.py:1.1.2.3 Tue Dec 24 13:04:46 2002
+++ Zope3/src/zope/app/rdb/gadfly/kjbuckets0.py Tue Dec 24 21:20:43 2002
@@ -11,942 +11,942 @@
return x.is_kjtable
except:
return 0
-
+
unhashable = "unhashable key error"
class kjGraph:
- is_kjtable = 1
+ is_kjtable = 1
- def __init__(self, *args):
- #print "kjGraph.__init__", args
- key_to_list = self.key_to_list = {}
- self.dirty = 0
- self.hashed = None
- #print args
- if args:
- if len(args)>1:
- raise ValueError, "only 1 or 0 argument supported"
- from types import IntType, ListType, TupleType
- arg = args[0]
- targ = type(arg)
- test = key_to_list.has_key
- if type(arg) is IntType:
- return # ignore int initializer (presize not implemented)
- elif type(arg) is ListType or type(arg) is TupleType:
- for (x,y) in arg:
- if test(x):
- key_to_list[x].append(y)
- else:
- key_to_list[x] = [y]
- return
- aclass = arg.__class__
- if aclass is kjGraph:
- aktl = arg.key_to_list
- for k in aktl.keys():
- key_to_list[k] = aktl[k][:]
- return
- if aclass is kjDict or aclass is kjSet:
- adict = arg.dict
- for k in adict.keys():
- key_to_list[k] = [ adict[k] ]
- return
- raise ValueError, "arg for kjGraph must be tuple, list, or kjTable"
-
[-=- -=- -=- 1838 lines omitted -=- -=- -=-]
else:
- print "values", X.values()
- print "keys", X.keys()
- print X, "inverted", ~X
- if not X.member(0,1):
- raise "member test fails (0,1)", X
- print "adding to", X
- X.add(999,888)
- print "added", X
- X.delete_arc(999,888)
- print "deleted", X
- if X.member(999,888):
- raise "member test fails (999,888)", X
- if X.has_key(999):
- raise "has_key fails 999", X
- if not X.has_key(0):
- raise "has_key fails 0", X
+ print "values", X.values()
+ print "keys", X.keys()
+ print X, "inverted", ~X
+ if not X.member(0,1):
+ raise "member test fails (0,1)", X
+ print "adding to", X
+ X.add(999,888)
+ print "added", X
+ X.delete_arc(999,888)
+ print "deleted", X
+ if X.member(999,888):
+ raise "member test fails (999,888)", X
+ if X.has_key(999):
+ raise "has_key fails 999", X
+ if not X.has_key(0):
+ raise "has_key fails 0", X
for Y in ALL:
print "Y", Y
if (X!=S and Y!=S):
- print "diff", X, Y
- print "%s-%s=%s" % (X,Y,X-Y)
+ print "diff", X, Y
+ print "%s-%s=%s" % (X,Y,X-Y)
elif X==S:
- D = kjSet(Y)
- print "diff", X, D
- print "%s-%s=%s" % (X,D,X-D)
+ D = kjSet(Y)
+ print "diff", X, D
+ print "%s-%s=%s" % (X,D,X-D)
print "%s+%s=%s" % (X,Y,X+Y)
print "%s&%s=%s" % (X,Y,X&Y)
print "%s*%s=%s" % (X,Y,X*Y)
=== Zope3/src/zope/app/rdb/gadfly/kjpylint.py 1.1.2.3 => 1.1.2.4 ===
--- Zope3/src/zope/app/rdb/gadfly/kjpylint.py:1.1.2.3 Tue Dec 24 13:04:46 2002
+++ Zope3/src/zope/app/rdb/gadfly/kjpylint.py Tue Dec 24 21:20:43 2002
@@ -42,7 +42,7 @@
Notes:
======
The lint process works, in outline, like this.
-Scan over a python program
+Scan over a python program
x = 1
@@ -80,7 +80,7 @@
from pygram import newlineresult
# reduction rules:
-# only need to consider
+# only need to consider
# expressions, assignments, def, class, global, import, from, for
#
# expressions return a list of unqualified names, not known set
@@ -133,9 +133,9 @@
for x in left:
(ln, ri, op, name) = x
if op == "ref":
- result.append( (ln, ri, "set", name) )
+ result.append( (ln, ri, "set", name) )
else:
- result.append(x)
+ result.append(x)
return result
#@R except2 :: except_clause >> except test , test
@@ -149,7 +149,7 @@
#@R smassn :: small_stmt >> assn
# ignored
-#@R rfrom :: import_stmt >> from dotted_name import name_list
+#@R rfrom :: import_stmt >> from dotted_name import name_list
#@R rfromc :: import_stmt >> from dotted_name import name_list ,
def rfrom(list, context):
@@ -166,7 +166,7 @@
lineno = L.lineno
# are we reducing on a newline?
if L.lastresult==newlineresult:
- lineno = lineno-1
+ lineno = lineno-1
return (lineno, -L.realindex, kind, thing)
#@R dn1 :: dotted_name >> NAME
@@ -205,7 +205,7 @@
return t2
# handles from case, make names set local
-#@R global1 :: global_stmt >> global NAME
+#@R global1 :: global_stmt >> global NAME
def global1(list, context):
#print "global1", list
@@ -213,7 +213,7 @@
#return [ (L.lineno, -L.realindex, "global", list[1]) ]
return [ mark("global", list[1], context) ]
-#@R globaln :: global_stmt >> global_stmt , NAME
+#@R globaln :: global_stmt >> global_stmt , NAME
# handles global, make names global (not set or reffed)
def globaln(list, context):
@@ -224,8 +224,8 @@
g.append( mark("global", n, context) )
return g
-#@R for1 :: for_stmt >>
-#for exprlist in testlist :
+#@R for1 :: for_stmt >>
+#for exprlist in testlist :
# suite
def for1(list, context):
@@ -234,10 +234,10 @@
refs = t + s
return assn(e, refs)
-#@R for2 :: for_stmt >>
-#for exprlist in testlist :
-# suite
-#else :
+#@R for2 :: for_stmt >>
+#for exprlist in testlist :
+# suite
+#else :
# suite
def for2(list,context):
@@ -282,7 +282,7 @@
params1c = params1
-#@R params2 :: varargslist >>
+#@R params2 :: varargslist >>
def params2(l, c):
return ([], [])
@@ -357,9 +357,9 @@
for (ln, ri, op, n) in l+g+suite:
lineno = min(lineno, ln)
if name is not None:
- result.append((lineno, -index, "set", name))
- # Note: this is to prevent complaints about unreffed functions
- result.append((lineno+1, -index, "qref", name))
+ result.append((lineno, -index, "set", name))
+ # Note: this is to prevent complaints about unreffed functions
+ result.append((lineno+1, -index, "qref", name))
return result
#@R testlambda1 :: test >> lambda varargslist : test
@@ -376,41 +376,41 @@
for x in var_accesses:
(ln, ri, op, name) = x
if op == "global":
- globals[name] = ln
+ globals[name] = ln
#result.append(x) (ignore global sets in local context)
# scan for locals
for (ln, ri, op, name) in var_accesses:
if op == "set" and not locals.has_key(name):
- if globals.has_key(name):
- context.complain(
- "Warning: set of global %s in local context %s" % (`name`, `sname`))
- result.append( (ln, ri, op, name) )
- pass # ignore global set in local context
- else:
- locals[name] = [ln, 0] # line assigned, #refs
+ if globals.has_key(name):
+ context.complain(
+ "Warning: set of global %s in local context %s" % (`name`, `sname`))
+ result.append( (ln, ri, op, name) )
+ pass # ignore global set in local context
+ else:
+ locals[name] = [ln, 0] # line assigned, #refs
# scan for use before assign, etc.
for x in var_accesses:
(ln, ri, op, name) = x
if locals.has_key(name):
- if op in ["ref", "qref"]:
- set = locals[name]
- set[1] = set[1] + 1
- assnln = set[0]
- if (ln <= assnln):
- context.complain(
- "(%s) local %s ref at %s before assign at %s" % (
- sname, `name`, ln, `assnln`))
+ if op in ["ref", "qref"]:
+ set = locals[name]
+ set[1] = set[1] + 1
+ assnln = set[0]
+ if (ln <= assnln):
+ context.complain(
+ "(%s) local %s ref at %s before assign at %s" % (
+ sname, `name`, ln, `assnln`))
elif op not in ("global", "set"):
- # ignore global sets in local context.
- result.append(x)
+ # ignore global sets in local context.
+ result.append(x)
# scan for no use
if not unused_ok:
- for (name, set) in locals.items():
- [where, count] = set
- if count<1:
- context.complain(
- "(%s) %s defined before %s not used" % (sname, `name`, where))
- return result
+ for (name, set) in locals.items():
+ [where, count] = set
+ if count<1:
+ context.complain(
+ "(%s) %s defined before %s not used" % (sname, `name`, where))
+ return result
### note, need to make special case for qualified names
#@R powera :: power >> atom trailerlist
@@ -419,16 +419,16 @@
#print "powera", list
[a, (t, full)] = list
if a and full:
- # atom is a qualified name
- (ln, ri, op, n) = a[0]
- result = [ (ln, ri, "qref", n) ]
+ # atom is a qualified name
+ (ln, ri, op, n) = a[0]
+ result = [ (ln, ri, "qref", n) ]
else:
- result = a
+ result = a
result = result + t
#print "returning", result
return result
-
-#@R trailerlist0 :: trailerlist >>
+
+#@R trailerlist0 :: trailerlist >>
def trailerlist0(list, context):
return ([], 0) # empty trailerlist
@@ -451,13 +451,13 @@
result = []
for x in list:
if type(x)==ListType:
- if result == []:
- if len(x)>0 and type(x[0])==ListType:
- raise "oops", x
- result = x
- else:
- for y in x:
- result.append(y)
+ if result == []:
+ if len(x)>0 and type(x[0])==ListType:
+ raise "oops", x
+ result = x
+ else:
+ for y in x:
+ result.append(y)
return result
def aname(list, context):
@@ -532,9 +532,9 @@
seen = {}
for (ln, ri, op, name) in globals:
if not seen.has_key(name) and op!="set":
- seen[name] = name
- self.complain(
- "%s: (%s) %s not defined in module?" % (ln, op, `name`))
+ seen[name] = name
+ self.complain(
+ "%s: (%s) %s not defined in module?" % (ln, op, `name`))
self.deferred = [] # reset state.
def patch_globals(self):
# patch in global names
=== Zope3/src/zope/app/rdb/gadfly/pygram.py 1.1.2.3 => 1.1.2.4 === (827/927 lines abridged)
--- Zope3/src/zope/app/rdb/gadfly/pygram.py:1.1.2.3 Tue Dec 24 13:04:46 2002
+++ Zope3/src/zope/app/rdb/gadfly/pygram.py Tue Dec 24 21:20:43 2002
@@ -4,7 +4,7 @@
# EDIT THIS: THE DIRECTORY IN WHICH TO MARSHAL THE
# GRAMMAR DATA STRUCTURES.
#
-ARCHIVE = "."
+ARCHIVE = "."
marshalfilename = ARCHIVE + "/pygram.mar"
@@ -66,7 +66,7 @@
@R assnnc :: assn >> testlist , = assn
-##testing @R exprassn :: expr_stmt >> expr_stmt = testlist
+##testing @R exprassn :: expr_stmt >> expr_stmt = testlist
@R exprlistc :: expr_stmt >> testlist ,
@@ -74,7 +74,7 @@
##7 kw print
@R rprint0 :: print_stmt >> print
-@R rprint :: print_stmt >> print testlist
+@R rprint :: print_stmt >> print testlist
@R rprintc :: print_stmt >> print testlist ,
##8 kw del
@@ -88,7 +88,7 @@
@R rbreak :: flow_stmt >> break
@R rcontinue :: flow_stmt >> continue
@R rreturn0 :: flow_stmt >> return
-@R rreturn :: flow_stmt >> return testlist
+@R rreturn :: flow_stmt >> return testlist
@R rreturnc :: flow_stmt >> return testlist ,
@R rraise1 :: flow_stmt >> raise test
@R rraise2 :: flow_stmt >> raise test , test
@@ -97,11 +97,11 @@
## 11 12 13 14 skipped
## 15 kw import from
-@R rimport :: import_stmt >> import dotted_name_list
+@R rimport :: import_stmt >> import dotted_name_list
@R rimportc :: import_stmt >> import dotted_name_list ,
@R dnlist1 :: dotted_name_list >> dotted_name
@R dnlistn :: dotted_name_list >> dotted_name_list , dotted_name
-@R rfrom :: import_stmt >> from dotted_name import name_list
+@R rfrom :: import_stmt >> from dotted_name import name_list
@R rfroms :: import_stmt >> from dotted_name import *
[-=- -=- -=- 827 lines omitted -=- -=- -=-]
+
+ d = {}
for i in range(10): d[i] = i
'''
def test(c,s):
- return "this"
+ return "this"
while not done:
print done
break
list = [1,2,3]
# comment
return 5
-
-
+
+
n,x = 89 >> 90 + 6 / 7 % x + z << 6 + 2 ** 8
if x==5:
@@ -978,17 +978,17 @@
'''
def test(grammar, context=None, teststring=teststring):
- from time import time
- now = time()
- x = grammar.DoParse1(teststring, context)
- elapsed = time()-now
- print x
- print elapsed
- return x
-
+ from time import time
+ now = time()
+ x = grammar.DoParse1(teststring, context)
+ elapsed = time()-now
+ print x
+ print elapsed
+ return x
+
regen = 0
dotest = 0
-
-if __name__ == "__main__" :
- if regen: GrammarBuild()
- unMarshalpygram()
+
+if __name__ == "__main__" :
+ if regen: GrammarBuild()
+ unMarshalpygram()
=== Zope3/src/zope/app/rdb/gadfly/relalg.py 1.1.2.3 => 1.1.2.4 ===
--- Zope3/src/zope/app/rdb/gadfly/relalg.py:1.1.2.3 Tue Dec 24 13:04:46 2002
+++ Zope3/src/zope/app/rdb/gadfly/relalg.py Tue Dec 24 21:20:43 2002
@@ -122,45 +122,45 @@
class relation:
- def __init__(self, names, rows):
- #print "relation init", names, rows
- names = self.names = tuple(names)
- nameset = self.nameset = kjSet(names)
- for r in rows:
- if nameset != kjSet(r.keys()):
- raise ValueError, \
- "bad names: "+`(names, r.items())`
- self.rows = kjSet(rows)
-
- def __repr__(self):
- from string import join
- names = self.names
- rows = self.rows.items()
- if not rows:
- nns = join(names)
- replist = [nns, "="*len(nns), " --<empty>--"]
- return join(replist, "\n")
- #print names, rows
- nnames = len(names)
- if nnames==1:
- replist = [names[0]]
- else:
- replist = [names]
- for r in rows:
- elt = r.dump(names)
- replist.append(r.dump(names))
- #print replist
- if nnames==1:
- replist = maxrep(replist)
- else:
- transpose = apply(map, tuple([None] + replist))
- adjusted = map(maxrep, transpose)
- replist = apply(map, tuple([None] + adjusted))
- replist = map(join, replist)
- replist.insert(1, "=" * len(replist[0]))
- #print replist
- return join(replist, "\n")
-
+ def __init__(self, names, rows):
+ #print "relation init", names, rows
+ names = self.names = tuple(names)
+ nameset = self.nameset = kjSet(names)
+ for r in rows:
+ if nameset != kjSet(r.keys()):
+ raise ValueError, \
+ "bad names: "+`(names, r.items())`
+ self.rows = kjSet(rows)
+
+ def __repr__(self):
+ from string import join
+ names = self.names
+ rows = self.rows.items()
+ if not rows:
+ nns = join(names)
+ replist = [nns, "="*len(nns), " --<empty>--"]
+ return join(replist, "\n")
+ #print names, rows
+ nnames = len(names)
+ if nnames==1:
+ replist = [names[0]]
+ else:
+ replist = [names]
+ for r in rows:
+ elt = r.dump(names)
+ replist.append(r.dump(names))
+ #print replist
+ if nnames==1:
+ replist = maxrep(replist)
+ else:
+ transpose = apply(map, tuple([None] + replist))
+ adjusted = map(maxrep, transpose)
+ replist = apply(map, tuple([None] + adjusted))
+ replist = map(join, replist)
+ replist.insert(1, "=" * len(replist[0]))
+ #print replist
+ return join(replist, "\n")
+
def maxrep(list):
list = map(str, list)
maxlen = max( map(len, list) )
@@ -356,11 +356,11 @@
this = rows[i]
lt = len(this)
if lt!=ln:
- raise ValueError, "names, vals don't match"+`(names,this)`
+ raise ValueError, "names, vals don't match"+`(names,this)`
if len(this)==1:
- this = this[0]
+ this = this[0]
else:
- this = tuple(this)
+ this = tuple(this)
rows[i] = kjUndump(names, this)
return relation(names, rows)
@@ -398,32 +398,32 @@
VARS = vars()
class punter:
- def __init__(self, name):
- self.name = name
- def __call__(self, list, context):
- print "punt:", self.name, list
- return list
-
+ def __init__(self, name):
+ self.name = name
+ def __call__(self, list, context):
+ print "punt:", self.name, list
+ return list
+
class tracer:
- def __init__(self, name, fn):
- self.name = name
- self.fn = fn
-
- def __call__(self, list, context):
- print "tracing", self.name, list
- test = self.fn(list, context)
- print self.name, "returns", test
- return test
+ def __init__(self, name, fn):
+ self.name = name
+ self.fn = fn
+
+ def __call__(self, list, context):
+ print "tracing", self.name, list
+ test = self.fn(list, context)
+ print self.name, "returns", test
+ return test
def BindRules(sqlg):
for name in sqlg.RuleNameToIndex.keys():
if VARS.has_key(name):
- #print "binding", name
- sqlg.Bind(name, VARS[name]) # nondebug
- #sqlg.Bind(name, tracer(name, VARS[name]) ) # debug
+ #print "binding", name
+ sqlg.Bind(name, VARS[name]) # nondebug
+ #sqlg.Bind(name, tracer(name, VARS[name]) ) # debug
else:
- print "unbound", name
- sqlg.Bind(name, punter(name))
+ print "unbound", name
+ sqlg.Bind(name, punter(name))
return sqlg
## snarfed from sqlgen
@@ -437,12 +437,12 @@
def userdeffn(str):
return str
-
+
charstre = "'[^\n']*'"
def charstfn(str):
return str[1:-1]
-
+
numlitre = "[%s][%s\.]*" % (string.digits, alphanum) # not really...
def numlitfn(str):
@@ -454,7 +454,7 @@
Grammar.Addterm("name", userdefre, userdeffn)
Grammar.Addterm("string", charstre, charstfn)
Grammar.Addterm("number", numlitre, numlitfn)
-
+
def Buildrelalg(filename=MARSHALFILE):
import kjParseBuild
SQLG = kjParseBuild.NullCGrammar()
@@ -474,7 +474,7 @@
SQLG.MarshalDump(outfile)
outfile.close()
return SQLG
-
+
def reloadrelalg(filename=MARSHALFILE):
import kjParser
filename = INSTALLDIR+"/"+filename
@@ -484,7 +484,7 @@
DeclareTerminals(SQLG)
BindRules(SQLG)
return SQLG
-
+
def runfile(f):
from string import split, join
ragram = reloadrelalg()
@@ -522,6 +522,3 @@
finally:
if not done:
print __doc__
-
-
-
=== Zope3/src/zope/app/rdb/gadfly/remotetest.py 1.1.2.3 => 1.1.2.4 ===
--- Zope3/src/zope/app/rdb/gadfly/remotetest.py:1.1.2.3 Tue Dec 24 13:04:46 2002
+++ Zope3/src/zope/app/rdb/gadfly/remotetest.py Tue Dec 24 21:20:43 2002
@@ -4,7 +4,7 @@
# create the database
g = gadfly()
-g.startup("dbtest", "dbtest") # assume directory "dbtest" exists
+g.startup("dbtest", "dbtest") # assume directory "dbtest" exists
# define a remote view class
import gfintrospect
@@ -18,7 +18,7 @@
the listing() list must return a list of values,
but for multiple columns it must return a list
of tuples with one entry for each column.
-
+
The remote view implementation may optionally
redefine __init__ also, please see gfintrospect.py
"""
@@ -26,7 +26,7 @@
# static: don't reconstruct internal structure for each query
# for more interesting views static will generally be 0
static = 1
-
+
def __init__(self, column_names=None, rowlist=None):
"""do whatever needed for initialization"""
if column_names is None:
@@ -35,14 +35,14 @@
rowlist = [(1,2,3), (4,5,6), (7,8,9)]
self.column_names = column_names
self.rowlist = rowlist
-
+
def listing(self):
"""return list of tuples of right sizes to match column_names.
for more interesting views this will do something more
complex ;).
"""
return self.rowlist
-
+
# create a table using default cols and rows
### Python code adding ANY remote views must be EXECUTED
### EACH TIME THE DATABASE LOADS!
@@ -82,4 +82,3 @@
print "join 2::"
print c.pp()
print
-
=== Zope3/src/zope/app/rdb/gadfly/sqlbind.py 1.1.2.3 => 1.1.2.4 === (556/656 lines abridged)
--- Zope3/src/zope/app/rdb/gadfly/sqlbind.py:1.1.2.3 Tue Dec 24 13:04:46 2002
+++ Zope3/src/zope/app/rdb/gadfly/sqlbind.py Tue Dec 24 21:20:43 2002
@@ -3,37 +3,37 @@
def elt0(list, context):
"""return first member of reduction"""
return list[0]
-
+
def elt1(list, context):
"""return second member"""
return list[1]
-
+
def elt2(list, context):
return list[2]
-
+
def returnNone(list, context):
return None
-
+
def stat1(list, context):
"""return list of len 1 of statements"""
return list
-
+
#def statn(list, context):
# """return a list of statement reductions"""
# [stat, semi, statlist] = list
# statlist.insert(0, stat)
# return statlist
-
+
def thingcommalist(l, c):
[thing, comma, list] = l
list.insert(0, thing)
return list
-
+
def listcommathing(l, c):
[list, comma, thing] = l
list.append(thing)
return list
-
+
statn = thingcommalist
selstat = elt0
insstat = elt0
@@ -51,13 +51,13 @@
[drop, view, name] = l
[-=- -=- -=- 556 lines omitted -=- -=- -=-]
@@ -596,30 +596,28 @@
VARS = vars()
class punter:
- def __init__(self, name):
- self.name = name
- def __call__(self, list, context):
- print "punt:", self.name, list
- return list
-
+ def __init__(self, name):
+ self.name = name
+ def __call__(self, list, context):
+ print "punt:", self.name, list
+ return list
+
class tracer:
- def __init__(self, name, fn):
- self.name = name
- self.fn = fn
-
- def __call__(self, list, context):
- print self.name, list
- return self.fn(list, context)
+ def __init__(self, name, fn):
+ self.name = name
+ self.fn = fn
+
+ def __call__(self, list, context):
+ print self.name, list
+ return self.fn(list, context)
def BindRules(sqlg):
for name in sqlg.RuleNameToIndex.keys():
if VARS.has_key(name):
- #print "binding", name
- sqlg.Bind(name, VARS[name]) # nondebug
- #sqlg.Bind(name, tracer(name, VARS[name]) ) # debug
+ #print "binding", name
+ sqlg.Bind(name, VARS[name]) # nondebug
+ #sqlg.Bind(name, tracer(name, VARS[name]) ) # debug
else:
- print "unbound", name
- sqlg.Bind(name, punter(name))
+ print "unbound", name
+ sqlg.Bind(name, punter(name))
return sqlg
-
-
=== Zope3/src/zope/app/rdb/gadfly/sqlgen.py 1.1.2.3 => 1.1.2.4 ===
--- Zope3/src/zope/app/rdb/gadfly/sqlgen.py:1.1.2.3 Tue Dec 24 13:04:46 2002
+++ Zope3/src/zope/app/rdb/gadfly/sqlgen.py Tue Dec 24 21:20:43 2002
@@ -16,12 +16,12 @@
def userdeffn(str):
from string import upper
return upper(str)
-
+
charstre = "'[^']*'"
def charstfn(str):
return str[1:-1]
-
+
#numlitre = "[%s][%s\.]*" % (string.digits, alphanum) # not really...
digits = string.digits
@@ -38,7 +38,7 @@
Grammar.Addterm("user_defined_name", userdefre, userdeffn)
Grammar.Addterm("character_string_literal", charstre, charstfn)
Grammar.Addterm("numeric_literal", numlitre, numlitfn)
-
+
def BuildSQL(filename=MARSHALFILE):
import kjParseBuild
from sqlgram import sqlrules, nonterms, keywords, puncts
@@ -62,7 +62,7 @@
SQLG.MarshalDump(outfile)
outfile.close()
return SQLG
-
+
def reloadSQLG(filename=MARSHALFILE):
"""does not bind any interpretation functions."""
import kjParser
@@ -71,11 +71,7 @@
infile.close()
DeclareTerminals(SQLG)
return SQLG
-
+
def getSQL():
from sqlwhere import filename
return reloadSQLG(filename)
-
-
-
-
=== Zope3/src/zope/app/rdb/gadfly/sqlgram.py 1.1.2.3 => 1.1.2.4 ===
--- Zope3/src/zope/app/rdb/gadfly/sqlgram.py:1.1.2.3 Tue Dec 24 13:04:46 2002
+++ Zope3/src/zope/app/rdb/gadfly/sqlgram.py Tue Dec 24 21:20:43 2002
@@ -34,11 +34,11 @@
@R dropview :: drop_view_statement >> DROP VIEW user_defined_name
## create view statement
-@R createview :: create_view_statement >>
+@R createview :: create_view_statement >>
CREATE VIEW user_defined_name optnamelist AS select_statement
@R optnamelist0 :: optnamelist >>
@R optnamelistn :: optnamelist >> ( namelist )
-
+
## drop index statement
@R dropindex :: drop_index_statement >> DROP INDEX user_defined_name
@@ -47,12 +47,12 @@
CREATE INDEX user_defined_name
ON user_defined_name
( namelist )
-
+
@R createuniqueindex :: create_index_statement >>
CREATE UNIQUE INDEX user_defined_name
ON user_defined_name
( namelist )
-
+
@R names1 :: namelist >> user_defined_name
@R namesn :: namelist >> namelist , user_defined_name
@@ -61,7 +61,7 @@
UPDATE user_defined_name
SET assns
optwhere
-
+
@R assn1 :: assns >> assn
@R assnn :: assns >> assns , assn
@R assn :: assn >> column_identifier = expression
@@ -82,7 +82,7 @@
@R coleltid :: colelt >> column_definition
@R coleltconstraint :: colelt >> column_constraint_definition
## column constraints deferred
-@R coldef :: column_definition >>
+@R coldef :: column_definition >>
column_identifier data_type optdefault optcolconstraints
## optdefault deferred
@R optdef0 :: optdefault >>
@@ -123,9 +123,9 @@
SELECT alldistinct select_list
FROM table_reference_list
optwhere optgroup opthaving optunion
-
-## @R psubselect :: sub_query >> ( sub_query )
-
+
+## @R psubselect :: sub_query >> ( sub_query )
+
@R selectx :: select_statement >>
sub_query
optorder_by
@@ -134,7 +134,7 @@
@R addistinct :: alldistinct >> DISTINCT
@R where0 :: optwhere >>
@R where1 :: optwhere >> WHERE search_condition
-@R group0 :: optgroup >>
+@R group0 :: optgroup >>
@R group1 :: optgroup >> GROUP BY colnamelist
@R colnames1 :: colnamelist >> column_name
@R colnamesn :: colnamelist >> colnamelist , column_name
@@ -164,7 +164,7 @@
@R trl1as :: table_reference_list >> user_defined_name AS user_defined_name
@R trlnas :: table_reference_list >> user_defined_name AS user_defined_name , table_reference_list
-## select list
+## select list
@R selectstar :: select_list >> *
@R selectsome :: select_list >> selectsubs
@R select1 :: selectsubs >> select_sublist
@@ -194,7 +194,7 @@
@R predicatege :: comparison_predicate >> expression > = expression
@R predicatene :: comparison_predicate >> expression < > expression
@R predbetween :: comparison_predicate >> expression BETWEEN expression AND expression
-@R prednotbetween :: comparison_predicate >>
+@R prednotbetween :: comparison_predicate >>
expression NOT BETWEEN expression AND expression
## exists predicate
=== Zope3/src/zope/app/rdb/gadfly/sqlgtest.py 1.1.2.3 => 1.1.2.4 ===
--- Zope3/src/zope/app/rdb/gadfly/sqlgtest.py:1.1.2.3 Tue Dec 24 13:04:46 2002
+++ Zope3/src/zope/app/rdb/gadfly/sqlgtest.py Tue Dec 24 21:20:43 2002
@@ -14,4 +14,4 @@
"select -1 from x",
"select -1e6j from x",
"insert into table1 (a,b,c) values (-1e6+3j, -34e10, 56j)"
-]
\ No newline at end of file
+]
=== Zope3/src/zope/app/rdb/gadfly/sqlmod.py 1.1.2.3 => 1.1.2.4 === (1244/1344 lines abridged)
--- Zope3/src/zope/app/rdb/gadfly/sqlmod.py:1.1.2.3 Tue Dec 24 13:04:46 2002
+++ Zope3/src/zope/app/rdb/gadfly/sqlmod.py Tue Dec 24 21:20:43 2002
@@ -31,7 +31,7 @@
#print "exception!"
#print sys.exc_type, sys.exc_value
return -1
-
+
def __coerce__(self, other):
return (self, other)
def cmp(self, other):
@@ -40,332 +40,332 @@
CTFMT = """\
CREATE TABLE %s (
- %s
+ %s
)"""
-
+
class CreateTable(Ordered_DDF):
- """create table operation"""
-
- def __init__(self, name, colelts):
- self.name = name
- self.colelts = colelts
- self.indb = None # db in which to create
-
- def initargs(self):
- return (self.name, [])
-
- def marshaldata(self):
- from sqlsem import serialize
- return map(serialize, self.colelts)
-
- def demarshal(self, args):
- from sqlsem import deserialize
- self.colelts = map(deserialize, args)
-
- def __repr__(self):
- from string import join
- elts = list(self.colelts)
- elts = map(repr, elts)
- return CTFMT % (self.name, join(elts, ",\n "))
-
- def relbind(self, db):
- """check that table doesn't already exist"""
- if db.has_relation(self.name):
- raise NameError, "cannot create %s, exists" % (self.name,)
- self.indb = db
[-=- -=- -=- 1244 lines omitted -=- -=- -=-]
- for k in tupsi.keys():
- new[ ("result", k) ] = tupsi[k]
- tups[i] = new
- return tups
-
+ def __init__(self, subsel):
+ self.subsel = subsel
+
+ def initargs(self):
+ return (self.subsel,)
+
+ def __repr__(self):
+ return "[subsel] %s" % (self.subsel,)
+
+ def resultexps(self):
+ # get list of result bindings
+ subsel = self.subsel
+ atts = self.subsel.attributes()
+ # bind each as "result.name"
+ exps = []
+ from sqlsem import BoundAttribute
+ for a in atts:
+ exps.append( BoundAttribute("result", a) )
+ return exps # temp
+
+ def relbind(self, db):
+ subsel = self.subsel
+ self.subsel = subsel.relbind(db)
+ # do nothing with domain for now
+ #subsel_domain = subsel.domain()
+ return self
+
+ def eval(self, dyn=None):
+ subsel = self.subsel
+ subsel.uncache()
+ rel = subsel.eval(dyn)
+ tups = rel.rows()
+ from sqlsem import BoundTuple ### temp
+ from sqlsem import kjbuckets
+ kjDict = kjbuckets.kjDict
+ for i in xrange(len(tups)):
+ tupsi = tups[i]
+ new = kjDict()
+ for k in tupsi.keys():
+ new[ ("result", k) ] = tupsi[k]
+ tups[i] = new
+ return tups
+
# ordering for archiving datadefs
ddf_order = [CreateTable, CreateIndex, CreateView]
=== Zope3/src/zope/app/rdb/gadfly/sqlsem.py 1.1.2.3 => 1.1.2.4 === (5273/5373 lines abridged)
--- Zope3/src/zope/app/rdb/gadfly/sqlsem.py:1.1.2.3 Tue Dec 24 13:04:46 2002
+++ Zope3/src/zope/app/rdb/gadfly/sqlsem.py Tue Dec 24 21:20:43 2002
@@ -1,5 +1,5 @@
-""" sql semantics
+""" sql semantics
"""
### trim unused methods.
@@ -22,7 +22,7 @@
except ImportError:
import kjbuckets0
kjbuckets = kjbuckets0
-
+
Tuple = kjbuckets.kjDict
Graph = kjbuckets.kjGraph
Set = kjbuckets.kjSet
@@ -30,7 +30,7 @@
import sys, traceback
### debug
#sys.stderr = sys.stdin
-
+
# operations on simple tuples, mostly from kjbuckets
#def maketuple(thing):
# """try to make a tuple from thing.
@@ -40,7 +40,7 @@
# if type(thing)==DictType:
# return Tuple(thing.items() )
# else: return Tuple(thing)
-
+
def no_ints_nulls(list):
"""in place remove all ints, Nones from a list (for null handling)"""
tt = type
@@ -49,8 +49,8 @@
count = 0
for x in list:
if tt(x) is not IntType and x is not nn:
- list[count] = x
- count = count+1
+ list[count] = x
+ count = count+1
del list[count:]
return list
@@ -62,7 +62,7 @@
self.relname = relname
self.attributes = attributes
[-=- -=- -=- 5273 lines omitted -=- -=- -=-]
+
class Parse_Context:
- """contextual information for parsing
- p.param() returns a new sequence number for external parameter.
- """
- # not serializable
-
- parameter_index = 0
-
- # no __init__ yet
- def param(self):
- temp = self.parameter_index
- self.parameter_index = temp+1
- return temp
-
- def ndynamic(self):
- return self.parameter_index
+ """contextual information for parsing
+ p.param() returns a new sequence number for external parameter.
+ """
+ # not serializable
+
+ parameter_index = 0
+
+ # no __init__ yet
+ def param(self):
+ temp = self.parameter_index
+ self.parameter_index = temp+1
+ return temp
+
+ def ndynamic(self):
+ return self.parameter_index
# update/delete/insert statements
import sqlmod
CreateTable = sqlmod.CreateTable
@@ -2939,12 +2939,11 @@
Add_Tuples = gfdb0.Add_Tuples
Erase_Tuples = gfdb0.Erase_Tuples
Reset_Tuples = gfdb0.Reset_Tuples
-
+
####### testing
# test helpers
#def tp(**kw):
# return maketuple(kw)
-
+
#def st(**kw):
# return BTPredicate(BoundTuple(r=kw))
-