Page Menu
Home
c4science
Search
Configure Global Search
Log In
Files
F65805997
sqlobject.py
No One
Temporary
Actions
Download File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Award Token
Subscribers
None
File Metadata
Details
File Info
Storage
Attached
Created
Thu, Jun 6, 08:50
Size
6 KB
Mime Type
text/x-python
Expires
Sat, Jun 8, 08:50 (1 d, 23 h)
Engine
blob
Format
Raw Data
Handle
18130007
Attached To
R3127 blackdynamite
sqlobject.py
View Options
#!/usr/bin/env python
################################################################
from
__future__
import
print_function
################################################################
import
copy
import
re
import
sys
import
datetime
################################################################
class
SQLObject
(
object
):
" The generic object related to entries in the database "
def
__getattr__
(
self
,
attr
):
if
attr
in
self
.
entries
:
return
self
.
entries
[
attr
]
else
:
raise
AttributeError
(
attr
)
def
__setattr__
(
self
,
attr
,
value
):
if
attr
==
'entries'
:
object
.
__setattr__
(
self
,
attr
,
value
)
entries
=
self
.
entries
if
attr
in
entries
:
self
.
__setitem__
(
attr
,
value
)
else
:
object
.
__setattr__
(
self
,
attr
,
value
)
def
__str__
(
self
):
# output = ""
keys
=
set
(
self
.
entries
.
keys
())
if
'id'
in
self
.
entries
:
keys
.
remove
(
'id'
)
keys
=
list
(
keys
)
if
'id'
in
self
.
entries
:
keys
=
[
'id'
]
+
keys
outputs
=
[]
for
k
in
keys
:
v
=
self
.
entries
[
k
]
outputs
+=
[
k
+
": "
+
str
(
v
)]
return
"
\n
"
.
join
(
outputs
)
def
__getitem__
(
self
,
index
):
return
self
.
entries
[
index
.
lower
()]
def
__setitem__
(
self
,
index
,
value
):
self
.
entries
[
index
.
lower
()]
=
value
def
commit
(
self
):
self
.
base
.
connection
.
commit
()
def
setEntries
(
self
,
params
):
self
.
prepare
()
for
p
,
val
in
params
.
iteritems
():
if
(
p
in
self
.
types
):
self
.
entries
[
p
]
=
val
def
setFields
(
self
,
constraints
):
for
cons
in
constraints
:
_regex
=
"(\w*)\s*=\s*(.*)"
match
=
re
.
match
(
_regex
,
cons
)
if
(
not
match
or
(
not
len
(
match
.
groups
())
==
2
)):
print
(
"malformed assignment: "
+
cons
)
sys
.
exit
(
-
1
)
key
=
match
.
group
(
1
)
.
lower
()
.
strip
()
val
=
match
.
group
(
2
)
if
(
key
not
in
self
.
types
):
print
(
"unknown key '{0}'"
.
format
(
key
))
print
(
"possible keys are:"
)
for
k
in
self
.
types
.
keys
():
print
(
"
\t
"
+
k
)
sys
.
exit
(
-
1
)
val
=
self
.
types
[
key
](
val
)
self
.
entries
[
key
]
=
val
def
__init__
(
self
,
base
):
self
.
entries
=
{}
self
.
foreign_keys
=
{}
self
.
allowNull
=
{}
self
.
types
=
{}
self
.
base
=
base
self
.
operators
=
{}
def
__copy__
(
self
):
raise
RuntimeError
(
'this code is obsolete: needs to be reviewed'
)
# _cp.types = self.types.copy()
# _cp.entries = self.entries.copy()
# _cp.id = self.id
# _cp.foreign_keys = self.foreign_keys.copy()
# _cp.allowNull = self.foreign_keys.copy()
# _cp.connection = self.connection.copy()
# return _cp
def
__deepcopy__
(
self
,
memo
):
_cp
=
type
(
self
)(
self
.
base
)
_cp
.
types
=
copy
.
deepcopy
(
self
.
types
.
copy
(),
memo
)
_cp
.
entries
=
copy
.
deepcopy
(
self
.
entries
.
copy
(),
memo
)
# _cp.id = self.id
_cp
.
foreign_keys
=
copy
.
deepcopy
(
self
.
foreign_keys
,
memo
)
_cp
.
allowNull
=
copy
.
deepcopy
(
self
.
foreign_keys
,
memo
)
_cp
.
connection
=
self
.
base
return
_cp
def
prepare
(
self
):
self
.
base
.
setObjectItemTypes
(
self
)
def
insert
(
self
):
params
=
list
()
# print (self.types)
ex_msg
=
""
for
key
,
value
in
self
.
types
.
items
():
if
key
==
"id"
:
continue
if
((
key
not
in
self
.
entries
)
and
(
key
not
in
self
.
allowNull
)):
ex_msg
+=
(
"key '"
+
key
+
"' must be given a value before proceeding insertion
\n
"
)
if
(
not
ex_msg
==
""
):
raise
Exception
(
"
\n
****************
\n
"
+
ex_msg
+
"****************
\n
"
)
for
key
,
value
in
self
.
entries
.
items
():
# print (key)
# print (self.types[key])
# print (value)
params
.
append
(
self
.
types
[
key
.
lower
()](
value
))
request
=
"""
INSERT INTO {0}.{1} ({2}) VALUES ({3}) RETURNING id
"""
.
format
(
self
.
base
.
schema
,
self
.
table_name
,
','
.
join
(
self
.
entries
.
keys
()),
','
.
join
([
"
%s
"
for
item
in
params
])),
params
return
request
def
delete
(
self
):
request
,
params
=
"DELETE FROM {0}.{1} WHERE id={2}"
.
format
(
self
.
base
.
schema
,
self
.
table_name
,
self
.
id
),
[]
self
.
base
.
performRequest
(
request
,
params
)
def
update
(
self
):
params
=
list
()
keys
=
list
()
for
key
,
value
in
self
.
entries
.
items
():
if
(
value
is
None
):
continue
_type
=
self
.
types
[
key
]
# print (_type)
# print (key)
# print (type(value))
if
(
_type
==
datetime
.
datetime
):
continue
# _type = str
keys
.
append
(
key
)
params
.
append
(
_type
(
value
))
request
=
"UPDATE {0}.{1} SET ({2}) = ({3}) WHERE id = {4}"
.
format
(
self
.
base
.
schema
,
self
.
table_name
,
','
.
join
(
keys
),
','
.
join
([
"
%s
"
for
item
in
params
]),
self
.
id
)
self
.
base
.
performRequest
(
request
,
params
)
def
getquoted
(
self
):
raise
RuntimeError
(
'code needs review'
)
# objs = [sql_adapt(member) for member in self._sql_members()]
# for obj in objs:
# if hasattr(obj, 'prepare'):
# obj.prepare(self._conn)
# quoted_objs = [obj.getquoted() for obj in objs]
# return '(' + ', '.join(quoted_objs) + ')'
def
createTableRequest
(
self
):
query_string
=
"CREATE TABLE {0}.{1} ( id SERIAL PRIMARY KEY,"
.
format
(
self
.
base
.
schema
,
self
.
table_name
)
for
key
,
value
in
self
.
types
.
items
():
if
(
value
==
float
):
type_string
=
"DOUBLE PRECISION"
elif
(
value
==
int
):
type_string
=
"INTEGER"
elif
(
value
==
str
):
type_string
=
"TEXT"
elif
(
value
==
bool
):
type_string
=
"BOOLEAN"
elif
(
value
==
datetime
.
datetime
):
type_string
=
"TIMESTAMP"
else
:
print
(
value
)
raise
Exception
(
"type '{0}' not handled"
.
format
(
value
))
query_string
+=
"{0} {1} "
.
format
(
key
,
type_string
)
if
(
key
not
in
self
.
allowNull
):
query_string
+=
" NOT NULL"
query_string
+=
","
for
key
,
value
in
self
.
foreign_keys
.
items
():
query_string
+=
"FOREIGN KEY ({0}) REFERENCES {1}.{2},"
.
format
(
key
,
self
.
base
.
schema
,
value
)
return
query_string
[:
-
1
]
+
");"
def
getMatchedObjectList
(
self
):
import
selector
sel
=
selector
.
Selector
(
self
.
base
)
return
sel
.
select
(
self
,
self
)
Event Timeline
Log In to Comment