I would like to validate sql strings, which are spread all over the
code, i.e. I run ("prepare") them against a database to see if it happy
with the statements. Spelling errors in sql have been a major pain for
me.
The statements will not be assembled from smaller pieces, but they will
not neccessarily be defined at module level. I could live with class
level, but method level would be best. And I definitely don't want to
parse the source file, but I am willing to mark the strings so it is
easier to tell sql from non-sql.
So the code will look like this
class Foo:(...):
def aQuery(...):
stmt = """
-- checkSql
select 1 from dual
"""
executeQuery()
at the end of the file I would like to write something like
if (...):
validateSql()
The validateSql() is the problem. It would be imported from elsewhere.
and has to do some serious magic. It would have to lookup its caller's
module, find all the classes (and methods, if we go that far) extract
the constants, check if any of them are an SQL statement and validate
it.
The problem is the first part: how can I lookup the callers module and
the classobjs defined in there? Or finding any constant strings in the
caller's module would also be just fine. Or is there a completely
different way to do such a thing? 12 1323
Martin Drautzburg wrote:
I would like to validate sql strings, which are spread all over the
code, i.e. I run ("prepare") them against a database to see if it happy
with the statements. Spelling errors in sql have been a major pain for
me.
The statements will not be assembled from smaller pieces, but they will
not neccessarily be defined at module level. I could live with class
level, but method level would be best. And I definitely don't want to
parse the source file, but I am willing to mark the strings so it is
easier to tell sql from non-sql.
So the code will look like this
class Foo:(...):
def aQuery(...):
stmt = """
-- checkSql
select 1 from dual
"""
executeQuery()
at the end of the file I would like to write something like
if (...):
validateSql()
The validateSql() is the problem. It would be imported from elsewhere.
and has to do some serious magic. It would have to lookup its caller's
module, find all the classes (and methods, if we go that far) extract
the constants, check if any of them are an SQL statement and validate
it.
The problem is the first part: how can I lookup the callers module and
the classobjs defined in there? Or finding any constant strings in the
caller's module would also be just fine. Or is there a completely
different way to do such a thing?
Since all strings are constants you could just tokenize the source code:
def strings(filenam e):
with open(filename, "rU") as instream:
for t in tokenize.genera te_tokens(instr eam.readline):
if t[0] == token.STRING:
yield eval(t[1])
def validateSQL(fil ename=None):
if filename is None:
# by default operate on the calling module
filename = sys._getframe(1 ).f_globals["__file__"]
for s in strings(filenam e):
print "validating ", repr(s)
Another option would be to mark SQL statements similar to gettext by
enclosing them in a function call
sql = SQL("select * from...")
and then defining SQL() as either a no-op in production or an actual
validation while you are debugging. Even simpler and safer would be to
always validate once:
def SQL(sql, checked=set()):
if sql in checked:
return True
if not valid_sql(sql): raise ValueError
checked.add(sql )
return sql
Peter
Peter Otten wrote:
Martin Drautzburg wrote:
>I would like to validate sql strings, which are spread all over the code, i.e. I run ("prepare") them against a database to see if it happy with the statements. Spelling errors in sql have been a major pain for me.
>
def validateSQL(fil ename=None):
if filename is None:
# by default operate on the calling module
filename = sys._getframe(1 ).f_globals["__file__"]
for s in strings(filenam e):
print "validating ", repr(s)
This involves parsing the file. I can see that it would even work on a
pyc file and it actually does solve the problem. Still (for the glory
of the human mind) I would like to do this without parsing a file, but
just the python internal memory.
Another option would be to mark SQL statements similar to gettext by
enclosing them in a function call
sql = SQL("select * from...")
and then defining SQL() as either a no-op in production or an actual
validation while you are debugging. Even simpler and safer would be to
always validate once:
def SQL(sql, checked=set()):
if sql in checked:
return True
if not valid_sql(sql): raise ValueError
checked.add(sql )
return sql
No this does not do the trick. I will not be able to validate an sql
statement bofore I run over the piece of code that uses it. Or I would
have to define all my sql = SQL stuff on module level, isn't id. I
mean, the problem is: when are those sql = SQL statement really
ececuted?
Martin Drautzburg wrote:
I would like to validate sql strings, which are spread all over the
code, .... The statements will not be assembled from smaller pieces,
but they will not neccessarily be defined at module level. I could
live with class level, ....
parse the source file, but I am willing to mark the strings so it is
easier to tell sql from non-sql.
... Or is there a completely different way to do such a thing?
How about using some variation of:
class _Dummy: pass
OLD_STYLE = type(_Dummy)
def generate_string s(module):
'''Generate <class<name<val uetriples for a module'''
for top_level_name in dir(module):
top_level_value = getattr(module, top_level_name)
if isinstance(top_ level_value, basestring): # strings
yield None, top_level_name, top_level_value
elif isinstance(top_ level_value, type): # new-style class
for name in dir(top_level_v alue):
value = getattr(top_lev el_value, name)
if isinstance(valu e, basestring):
yield top_level_name, name, value
def sometest(somest ring):
'''Your criteria for "is an SQL string and has misspellings".' ''
return len(somestring) 20 and '
def investigate(mod ule):
for modname in sys.argv[1:]:
for class_, name, text in generate_string s(
__import__(modn ame)):
if remarkable(text ):
if class_ is None:
print 'Look at %s's top-level string %s.' % (
modname, name)
else:
print "Look at %s, class %s, string %s.' %
modname, class_, name)
if __name__ == '__main__':
import sys
for modname in sys.argv[1: ]:
investigate(mod name, sometest)
--
--Scott David Daniels sc***********@a cm.org
On Apr 21, 4:16 pm, Martin Drautzburg <Martin.Drautzb ...@web.de>
wrote:
I would like to validate sql strings, which are spread all over the
code, i.e. I run ("prepare") them against a database to see if it happy
with the statements. Spelling errors in sql have been a major pain for
me.
The statements will not be assembled from smaller pieces, but they will
not neccessarily be defined at module level. I could live with class
level, but method level would be best. And I definitely don't want to
parse the source file, but I am willing to mark the strings so it is
easier to tell sql from non-sql.
So the code will look like this
class Foo:(...):
def aQuery(...):
stmt = """
-- checkSql
select 1 from dual
"""
executeQuery()
at the end of the file I would like to write something like
if (...):
validateSql()
The validateSql() is the problem. It would be imported from elsewhere.
and has to do some serious magic. It would have to lookup its caller's
module, find all the classes (and methods, if we go that far) extract
the constants, check if any of them are an SQL statement and validate
it.
The problem is the first part: how can I lookup the callers module and
the classobjs defined in there? Or finding any constant strings in the
caller's module would also be just fine. Or is there a completely
different way to do such a thing?
Yes, there is: use an ORM to do the SQL generation for you. Check out
SQLAlchemy, it will buy you much more than what you asked for.
George
Martin Drautzburg <Ma************ ***@web.dewrote :
...
The problem is the first part: how can I lookup the callers module and
the classobjs defined in there? Or finding any constant strings in the
caller's module would also be just fine. Or is there a completely
different way to do such a thing?
Don't do black magic in production code.
For just hacking around, see sys._getframe -- it can give you a frame
object from where you can introspect into your caller's globals -- and
the inspect module of the standard Python library.
But don't put such black magic in production. The completely different
way is: just don't.
Alex
Martin Drautzburg wrote:
def SQL(sql, checked=set()):
*****if*sql*in* checked:
*********return *True
*****if*not*val id_sql(sql):*ra ise*ValueError
*****checked.ad d(sql)
*****return*sql
No this does not do the trick. I will not be able to validate an sql
statement bofore I run over the piece of code that uses it. Or I would
have to define all my sql = SQL stuff on module level, isn't id. I
mean, the problem is: when are those sql = SQL statement really
ececuted?
Let's see:
>>def SQL(sql):
.... print sql
....
>>a = SQL("module")
module # that one was obvious
>>class A:
.... b = SQL("class")
.... def method(self, c=SQL("default arg")):
.... d = SQL("method")
....
class # ha, class statements are executed, too...
default arg # ...as are default arguments
Peter
George Sakkis wrote:
Yes, there is: use an ORM to do the SQL generation for you. Check out
SQLAlchemy, it will buy you much more than what you asked for.
Might look, though in general I don't like OR mappers much. Having SQL
generated feels as strange as having python code generated. Too much
magic, too many layers. I think it is better to simply learn SQL.
And I don't really believe in OO databases much. OO databases have been
around for several decades and still have not reached the maturity of
relational databases. My feeling is that OO and persistence to not play
together well.
Peter Otten wrote:
>>>def SQL(sql):
... * * print sql
...
>>>a = SQL("module")
module # that one was obvious
>>>class A:
... * * b = SQL("class")
... * * def method(self, c=SQL("default arg")):
... * * * * * * d = SQL("method")
...
You are my hero. Indeed very cool!
In article <1h************ *************** @mac.com>,
Alex Martelli <al***@mac.comw rote:
>Martin Drautzburg <Ma************ ***@web.dewrote :
>> The problem is the first part: how can I lookup the callers module and the classobjs defined in there? Or finding any constant strings in the caller's module would also be just fine. Or is there a completely different way to do such a thing?
Don't do black magic in production code.
For just hacking around, see sys._getframe -- it can give you a frame object from where you can introspect into your caller's globals -- and the inspect module of the standard Python library.
But don't put such black magic in production. The completely different way is: just don't.
Could you expand on that? After all, that's exactly what we do to
implement a super() that works with classic classes -- and it's certainly
production code.
--
Aahz (aa**@pythoncra ft.com) <* http://www.pythoncraft.com/
"...string iteration isn't about treating strings as sequences of strings,
it's about treating strings as sequences of characters. The fact that
characters are also strings is the reason we have problems, but characters
are strings for other good reasons." --Aahz This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Zombie |
last post by:
Hi,
Can I have 2 namespaces in the same XML schema?
In the schema, I wish to declare elements such that some of them
belong to one namespace and others belong to a second namespace. Is
this possible? Note that both the namespaces should be in the same
schema and same xsd file. Could somebody provide a small snippet on
how to do this?
Thanks for your time.
|
by: sinister |
last post by:
I wanted to spiff up my overly spartan homepage, and started using some CSS
templates I found on a couple of weblogs. It looks fine in my browser (IE
6.0), but it doesn't print right. I tested the blogs, and one definitely
didn't print right.
Surveying the web, my impression is that CSS is very unreliable, because
even updated browsers fail to implement the standards correctly.
So should one just avoid CSS? Or is it OK if used...
|
by: Steven T. Hatton |
last post by:
I suspect the core language is not the level at which introspection should
be implemented in C++. That has been the choice of C#, and Java. Both of
these languages made some trade-offs to accomplish this. Like threading,
introspection can probably be implemented by third party providers. I tend
to favor open standards that are acceptted and respected by a significant
portion of the developers working in the field. Stroustrup states the...
|
by: Steven T. Hatton |
last post by:
Has there been any substantial progress toward supporting
introspection/reflection in C++?
I don't intend to mean it should be part of the Standard. It would,
nonetheless, be nice to have a generally accepted means of providing
introspection.
My inclination is to have two general categories of introspection: dynamic
introspection, and static intospection. In situations where it makes sense
to use virtual functions and their...
|
by: Dan Bass |
last post by:
There's an XML message I have, that has no namespace information.
Then there is a XSD schema that is must validate against, but this has a
targetNamespace and xmlns of "http://www.wbf.org/xml/b2mml-v02".
How do I get this XML to validate against the Schema in C#?
If I use XmlSpy (2005 home edition) to perform the validation, it first
inserts namespace and schema information into the XML before validating.
Validation then seems to work if...
| |
by: Wilfredo Sánchez Vega |
last post by:
I'm having some issues around namespace handling with XML:
>>> document = xml.dom.minidom.Document()
>>> element = document.createElementNS("DAV:", "href")
>>> document.appendChild(element)
<DOM Element: href at 0x1443e68>
>>> document.toxml()
'<?xml version="1.0" ?>\n<href/>'
Note that the namespace wasn't emitted. If I have PyXML,
|
by: Florian Daniel Otel |
last post by:
Hello all,
As the subject says, I am a newcomer to Python and I have a newcomer
question wrt namespaces and variable scope. Obviously, I might be
missing smth obvious, so TIA for the patience and/or pointers to
relevant resources
My problem: I just discovered (by mistake) that attempting to assign a
value to a non-local dictionary/list member does NOT generate an "
UnboundLocalError" exception and the assignment is preserved upon
|
by: Dave Rahardja |
last post by:
Is there a way to generate a series of statements based on the data members of
a structure at compile time?
I have a function that reverses the endianness of any data structure:
/// Reverse the endianness of a data structure "in place".
template <typename T>
void reverseEndian(T&);
Using boost, it is possible to provide the default implementation for all POD
|
by: noosaj |
last post by:
Hello,
I use vs2005 and I'm a college student studying programming. I'm
currently enrolled in a visual basic programming class.
I have one question, and I apologize if it sounds dumb. What are
namespaces?
Thanks!
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
| |
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |