29
29
30
30
_logger = logging .getLogger (__name__ )
31
31
32
+ ON_DELETE_ACTIONS = frozenset (("SET NULL" , "CASCADE" , "RESTRICT" , "NO ACTION" , "SET DEFAULT" ))
33
+
32
34
33
35
class PGRegexp (str ):
34
36
"""
@@ -290,8 +292,25 @@ def create_column(cr, table, column, definition, **kwargs):
290
292
# Manual PEP 3102
291
293
no_def = object ()
292
294
default = kwargs .pop ("default" , no_def )
295
+ fk_table = kwargs .pop ("fk_table" , no_def )
296
+ on_delete_action = kwargs .pop ("on_delete_action" , no_def )
293
297
if kwargs :
294
298
raise TypeError ("create_column() got an unexpected keyword argument %r" % kwargs .popitem ()[0 ])
299
+
300
+ fk = ""
301
+ if fk_table is not no_def :
302
+ if on_delete_action is no_def :
303
+ on_delete_action = "NO ACTION"
304
+ elif on_delete_action not in ON_DELETE_ACTIONS :
305
+ raise ValueError ("unexpected value for the `on_delete_action` argument: %r" % (on_delete_action ,))
306
+ fk = (
307
+ sql .SQL ("REFERENCES {}(id) ON DELETE {}" )
308
+ .format (sql .Identifier (fk_table ), sql .SQL (on_delete_action ))
309
+ .as_string (cr ._cnx )
310
+ )
311
+ elif on_delete_action is not no_def :
312
+ raise ValueError ("`on_delete_action` argument can only be used if `fk_table` argument is set." )
313
+
295
314
aliases = {
296
315
"boolean" : "bool" ,
297
316
"smallint" : "int2" ,
@@ -312,13 +331,15 @@ def create_column(cr, table, column, definition, **kwargs):
312
331
if curtype :
313
332
if curtype != definition :
314
333
_logger .error ("%s.%s already exists but is %r instead of %r" , table , column , curtype , definition )
334
+ if fk_table is not no_def :
335
+ create_fk (cr , table , column , fk_table , on_delete_action )
315
336
if default is not no_def :
316
337
query = 'UPDATE "{0}" SET "{1}" = %s WHERE "{1}" IS NULL' .format (table , column )
317
338
query = cr .mogrify (query , [default ]).decode ()
318
339
parallel_execute (cr , explode_query_range (cr , query , table = table ))
319
340
return False
320
341
321
- create_query = """ALTER TABLE "%s" ADD COLUMN "%s" %s""" % (table , column , definition )
342
+ create_query = """ALTER TABLE "%s" ADD COLUMN "%s" %s %s """ % (table , column , definition , fk )
322
343
if default is no_def :
323
344
cr .execute (create_query )
324
345
else :
@@ -328,7 +349,7 @@ def create_column(cr, table, column, definition, **kwargs):
328
349
329
350
330
351
def create_fk (cr , table , column , fk_table , on_delete_action = "" ):
331
- assert on_delete_action in { "SET NULL" , "CASCADE" , "RESTRICT" , "NO ACTION" , "SET DEFAULT" , "" }
352
+ assert on_delete_action in ON_DELETE_ACTIONS | { "" }
332
353
on_delete = "" if not on_delete_action else "ON DELETE {}" .format (on_delete_action )
333
354
cr .execute (
334
355
"""
0 commit comments