Skip to content

Commit

Permalink
added ironpython support
Browse files Browse the repository at this point in the history
  • Loading branch information
bart mosley committed Nov 21, 2010
1 parent 12cd467 commit aefb822
Show file tree
Hide file tree
Showing 16 changed files with 1,367 additions and 1 deletion.
Empty file added Ipy/README
Empty file.
39 changes: 39 additions & 0 deletions Ipy/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
'''
autumnIpy
A modification of the autumn ORM, http://autumn-orm.org, to
work with IronPython and the .NET
framework employed by Resolver One http://www.resolversystems.com.
'''
__version__ = (0, 0, 1)

__copyright__="""
Copyright (c) 2010 BG Research LLC
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""

from model import Model, DBConnection, Query
from filter import Filter
from relations import OneToMany, ForeignKey, JoinBy
from validators import *

117 changes: 117 additions & 0 deletions Ipy/dbconnection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
'''
Database and connection string configurations
'''
try:
from System.Data.Odbc import OdbcConnection, OdbcDataAdapter, OdbcCommand
except:
from resolverlib import *
from System.Data.Odbc import OdbcConnection, OdbcDataAdapter, OdbcCommand
finally:
from System.Data import DataSet, ConnectionState

def escape(string):
'''
Use to make sure table names are sql safe.
'''
return '`%s`' % string

def unescape(string):
return string.strip('`')

def sqlPlaceholder(datatype):
if (datatype == 'System.String' or
datatype == 'System.DateTime' or
datatype == 'System.TimeSpan' or
datatype == str):
return '"%s"'

return '%s'

class DBConnection(object):
def __init__(self, **kwargs):
defaultKeys = {'UID': None,
'PWD': None,
'DATABASE': None,
'DRIVER': "{MySQL ODBC 5.1 Driver}",
'SERVER': "localhost"}
defaultErrorString = "DBConnection: Value for %s must be provided"

# if parameters are provided, use them,
# if one of the default keys is not provided, use the default
self._connectionKeys = kwargs
for k in defaultKeys:
val = defaultKeys.get(k, None)
if not val:
assert k in kwargs, defaultErrorString % k
self._connectionKeys[k] = kwargs.get(k, val)

self._setConnectionString()
self._connection = OdbcConnection(self.connectionString)
self.placeholder = '%s'
self.insert = {"REPLACE": "REPLACE INTO %s (%s) VALUES (%s)",
"IGNORE": "INSERT IGNORE INTO %s (%s) VALUES (%s)",
"FAIL": "INSERT INTO %s (%s) VALUES (%s)"}

def _setConnectionString(self):
self._connectionString = ";".join(["=".join((k, self._connectionKeys[k]))
for k in self._connectionKeys])
def _getConnectionString(self):
'''
TODO: mask the password.
'''
return self._connectionString

def _getConnection(self):
return self._connection

def executeDBNonQuery(self, sql, CloseIt=True):
'''
Executes a non-query command against the database
'''
command = OdbcCommand(sql, self.connection)
if not (self.connection.State == ConnectionState.Open):
self.connection.Open()
rc = command.ExecuteNonQuery()

if CloseIt:
self.connection.Close()
return rc


def executeDBQuery(self, sql, rowsAsDict=None):
'''
Executes a query against the database, return the results in a list,
mimicking the fetchall feature of MySQLdb.
TODO: could use "GetDataTypeName" methods to return formating strings.
'''
reader = self.getReader(sql)

fetchall = []
while reader.Read():
row = tuple([reader.GetValue(n) for n in range(reader.FieldCount)])
if rowsAsDict:
rowNames = tuple([reader.GetName(n) for n in range(reader.FieldCount)])
row = dict(zip(rowNames, row))
fetchall.append(row)

#clean-up connections
reader.Close()
self.connection.Close()

return fetchall

def getReader(self, sql):
'''
Executes a non-query command against the database. User must close the reader
when finished.
'''
command = OdbcCommand(sql, self.connection)
if not (self.connection.State == ConnectionState.Open):
self.connection.Open()
reader = command.ExecuteReader()

return reader

connectionString = property(_getConnectionString, _setConnectionString)
connection = property(_getConnection)
102 changes: 102 additions & 0 deletions Ipy/filter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
'''
Filter class for sql queries.
'''

class Filter(object):
'''
Provides the ability to create queries using >,<, !=, etc.
Functions are defined as staticmethods, so no need to instatiate.
Usage:
say the model MyModel includes a numeric field 'amount'
>>> q = Query(model=MyModel).filter(amount = Filter.gt(100))
returns the records where amount > 100
'''
@staticmethod
def _output(op, value=None, column=None):
if not value and column:
return (op % escape(column),)
if value:
return (op, value)
else:
return (op,)

@staticmethod
def isnull():
return Filter._output(" is Null", None)

@staticmethod
def notnull():
return Filter._output(" is NOT Null", None)

@staticmethod
def gt(value=None, column=None): # Have class Column inherit from Filter, to just get op and % the value?
return Filter._output(">%s", value, column)

@staticmethod
def ge(value=None, column=None):
return Filter._output(">=%s", value, column)

@staticmethod
def lt(value=None, column=None):
return Filter._output("<%s", value, column)

@staticmethod
def le(value=None, column=None):
return Filter._output("<=%s", value, column)

@staticmethod
def ne(value=None, column=None):
return Filter._output("!=%s", value, column)

@classmethod
def eq(cls, value=None, column=None):
if not column and not value:
return cls.isnull()
return Filter._output("=%s", value, column)

@staticmethod
def between(value1, value2, NOTflag=None):
op = " NOT BETWEEN %s AND %s" if NOTflag else " BETWEEN %s AND %s"
lval = min(value1, value2)
uval = max(value1, value2)
return (op, lval, uval)

@staticmethod
def isin(value):
if hasattr(value, "__iter__"):
if len(value) > 1:
return Filter._output(" IN %s" % str(tuple(value)),)
else:
value = value[0]
return Filter.eq(value)

@staticmethod
def islike(value):
return Filter._output(" LIKE %s", value)

@staticmethod
def _getvalue(value):
if isinstance(value,tuple):
try:
return value[1]
except IndexError:
return value
else:
return value

@staticmethod
def _extractvalue(value):
if isinstance(value,tuple) and len(value)==1:
return False
return True

@staticmethod
def _extractvalues(itervals):
ll = []
for x in itervals:
if hasattr(x, "__iter__"):
ll.extend(x[1:])
else:
ll.append(x)
return ll
Loading

0 comments on commit aefb822

Please sign in to comment.