petit nettoyage

This commit is contained in:
Emmanuel Viennet 2021-08-01 17:33:09 +03:00
parent 80dd25ba02
commit 6cd868b7a3
4 changed files with 6 additions and 81 deletions

View File

@ -212,7 +212,6 @@ def DBSelectArgs(
+ limit + limit
+ offset + offset
) )
# open('/tmp/select.log','a').write( req % vals + '\n' )
try: try:
cursor.execute(req, vals) cursor.execute(req, vals)
except: except:
@ -259,9 +258,6 @@ def DBDelete(cnx, table, colid, val, commit=False):
# -------------------------------------------------------------------- # --------------------------------------------------------------------
# REQLOG = open('/tmp/req.log', 'w') # DEBUG
# REQN = 0
class EditableTable(object): class EditableTable(object):
"""--- generic class: SQL table with create/edit/list/delete""" """--- generic class: SQL table with create/edit/list/delete"""
@ -276,7 +272,6 @@ class EditableTable(object):
input_formators={}, input_formators={},
aux_tables=[], aux_tables=[],
convert_null_outputs_to_empty=True, convert_null_outputs_to_empty=True,
callback_on_write=None,
allow_set_id=False, allow_set_id=False,
html_quote=True, html_quote=True,
fields_creators={}, # { field : [ sql_command_to_create_it ] } fields_creators={}, # { field : [ sql_command_to_create_it ] }
@ -290,16 +285,13 @@ class EditableTable(object):
self.output_formators = output_formators self.output_formators = output_formators
self.input_formators = input_formators self.input_formators = input_formators
self.convert_null_outputs_to_empty = convert_null_outputs_to_empty self.convert_null_outputs_to_empty = convert_null_outputs_to_empty
self.callback_on_write = (
callback_on_write # called after each modification (USELESS and unused)
)
self.allow_set_id = allow_set_id self.allow_set_id = allow_set_id
self.html_quote = html_quote self.html_quote = html_quote
self.fields_creators = fields_creators self.fields_creators = fields_creators
self.filter_nulls = filter_nulls self.filter_nulls = filter_nulls
self.sql_default_values = None self.sql_default_values = None
def create(self, cnx, args, has_uniq_values=False): def create(self, cnx, args):
"create object in table" "create object in table"
vals = dictfilter(args, self.dbfields, self.filter_nulls) vals = dictfilter(args, self.dbfields, self.filter_nulls)
if self.id_name in vals and not self.allow_set_id: if self.id_name in vals and not self.allow_set_id:
@ -307,7 +299,7 @@ class EditableTable(object):
if self.html_quote: if self.html_quote:
quote_dict(vals) # quote all HTML markup quote_dict(vals) # quote all HTML markup
# format value # format value
for title in vals.keys(): for title in vals:
if title in self.input_formators: if title in self.input_formators:
vals[title] = self.input_formators[title](vals[title]) vals[title] = self.input_formators[title](vals[title])
# insert # insert
@ -319,23 +311,11 @@ class EditableTable(object):
% {"id_name": self.id_name, "table_name": self.table_name, "oid": oid} % {"id_name": self.id_name, "table_name": self.table_name, "oid": oid}
) )
new_id = cursor.fetchone()[0] new_id = cursor.fetchone()[0]
if has_uniq_values: # XXX probably obsolete
# check all tuples (without id_name) are UNIQUE !
res = DBSelectArgs(cnx, self.table_name, vals, what=[self.id_name])
if len(res) != 1:
# BUG !
log("create: BUG table_name=%s args=%s" % (self.table_name, str(args)))
assert len(res) == 1, "len(res) = %d != 1 !" % len(res)
if self.callback_on_write:
self.callback_on_write()
return new_id return new_id
def delete(self, cnx, oid, commit=True): def delete(self, cnx, oid, commit=True):
"delete tuple" "delete tuple"
DBDelete(cnx, self.table_name, self.id_name, oid, commit=commit) DBDelete(cnx, self.table_name, self.id_name, oid, commit=commit)
if self.callback_on_write:
self.callback_on_write()
def list( def list(
self, self,
@ -349,10 +329,6 @@ class EditableTable(object):
offset="", offset="",
): ):
"returns list of dicts" "returns list of dicts"
# REQLOG.write('%s: %s by %s (%s) %d\n'%(self.table_name,args,sys._getframe(1).f_code.co_name, sys._getframe(2).f_code.co_name, REQN))
# REQLOG.flush()
# global REQN
# REQN = REQN + 1
vals = dictfilter(args, self.dbfields, self.filter_nulls) vals = dictfilter(args, self.dbfields, self.filter_nulls)
if not sortkey: if not sortkey:
sortkey = self.sortkey sortkey = self.sortkey
@ -408,60 +384,10 @@ class EditableTable(object):
where="%s=%%(%s)s" % (self.id_name, self.id_name), where="%s=%%(%s)s" % (self.id_name, self.id_name),
commit=True, commit=True,
) )
if self.callback_on_write:
self.callback_on_write()
def get_sql_default_values(self, cnx):
"return dict with SQL default values for each field"
if self.sql_default_values is None: # not cached
# We insert a new tuple, get the values and delete it
# XXX non, car certaines tables ne peuvent creer de tuples
# a default, a cause des references ou contraintes d'intégrité.
# oid = self.create(cnx, {})
# vals = self.list(cnx, args= {self.id_name : oid})[0]
# self.delete(cnx, oid)
# self.sql_default_values = vals
#
# Méthode spécifique à postgresql (>= 7.4)
cursor = cnx.cursor(cursor_factory=ScoDocCursor)
cursor.execute(
"SELECT column_name, data_type, column_default FROM information_schema.columns WHERE table_name = '%s'"
% self.table_name
)
d = {}
for info in cursor.dictfetchall():
v = info["column_default"]
# strip type information if present (eg 'hello'::text)
if v:
v = v.split("::")[0]
# convert type to Python type
if v:
if info["data_type"] == "text":
log('get: v="%s"' % v)
if v[0] == v[-1] == "'":
v = v[1:-1] # strip quotes
elif v[:2] == "E'" and v[-1] == "'":
v = v[2:-1] # postgresql string with escapes
v = v.replace(
"\\012", "\n"
) # fix (je ne comprend pas bien pourquoi les valeurs sont ici quotées, ce n'est pas le cas dans les tables ordinaires)
v = v.replace("''", "'") # idem
log('--> v="%s"' % v)
elif info["data_type"] == "real":
v = float(v)
elif info["data_type"] == "integer":
v = int(v)
# elif info['data_type'] == 'date':
# pass # XXX todo
else:
log("Warning: unhandled SQL type in get_sql_default_values")
d[info["column_name"]] = v
self.sql_default_values = d
return self.sql_default_values
def dictfilter(d, fields, filter_nulls=True): def dictfilter(d, fields, filter_nulls=True):
# returns a copy of d with only keys listed in "fields" and non null values """returns a copy of d with only keys listed in "fields" and non null values"""
r = {} r = {}
for f in fields: for f in fields:
if f in d and (d[f] != None or not filter_nulls): if f in d and (d[f] != None or not filter_nulls):
@ -469,7 +395,6 @@ def dictfilter(d, fields, filter_nulls=True):
val = d[f].strip() val = d[f].strip()
except: except:
val = d[f] val = d[f]
# if val != '': not a good idea: how to suppress a field ?
r[f] = val r[f] = val
return r return r

View File

@ -734,7 +734,7 @@ scolar_events_edit = _scolar_eventsEditor.edit
def scolar_events_create(cnx, args): def scolar_events_create(cnx, args):
# several "events" may share the same values # several "events" may share the same values
_scolar_eventsEditor.create(cnx, args, has_uniq_values=False) _scolar_eventsEditor.create(cnx, args)
# -------- # --------

View File

@ -109,7 +109,7 @@ def add(typ, object=None, text="", url=None, max_frequency=False):
_LAST_NEWS[(authuser_name, typ, object)] = t _LAST_NEWS[(authuser_name, typ, object)] = t
_send_news_by_mail(args) _send_news_by_mail(args)
return scolar_news_create(cnx, args, has_uniq_values=False) return scolar_news_create(cnx, args)
def scolar_news_summary(context, n=5): def scolar_news_summary(context, n=5):

View File

@ -1848,7 +1848,7 @@ def appreciation_add_form(
args["id"] = id args["id"] = id
sco_etud.appreciations_edit(cnx, args) sco_etud.appreciations_edit(cnx, args)
else: # nouvelle else: # nouvelle
sco_etud.appreciations_create(cnx, args, has_uniq_values=False) sco_etud.appreciations_create(cnx, args)
# log # log
logdb( logdb(
cnx, cnx,