Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Derby - constraints

Tags:

sql

schema

derby

In the Derby server, how can you use the information in the system tables of the schema to create a select statement in order to retrieve the constraint names for each table?

like image 506
Artem Barger Avatar asked May 10 '09 18:05

Artem Barger


2 Answers

The relevant manual is the Derby Reference Manual. There are many versions available: 10.13 was current in April 2017, but it was 10.3 in May 2009.

Original answer

SELECT c.constraintname, t.tablename
    FROM sysconstraints c, systables t
    WHERE c.tableid = t.tableid;

Since sufficiently recent versions of Derby require that the system catalogue tables are prefixed by sys. (10.13 is quoted by kiwicomb123 in a comment), you can revise the query to use the explicit JOIN notation too, and use:

SELECT c.constraintname, t.tablename
  FROM sys.sysconstraints c
  JOIN sys.systables t
    ON c.tableid = t.tableid;

You can add extra columns — for example, c.type to get the constraint type.

like image 138
Jonathan Leffler Avatar answered Oct 21 '22 07:10

Jonathan Leffler


SELECT sc.schemaname, co.constraintname, t.tablename, cg.descriptor, t2.tablename, cg2.descriptor, f.deleterule, f.updaterule
FROM sys.sysconstraints co
JOIN sys.sysschemas sc ON co.schemaid = sc.schemaid
JOIN sys.systables t ON co.tableid = t.tableid
JOIN sys.sysforeignkeys f ON co.constraintid = f.constraintid
JOIN sys.sysconglomerates cg ON f.conglomerateid = cg.conglomerateid
JOIN sys.sysconstraints co2 ON f.keyconstraintid = co2.constraintid
JOIN sys.systables t2 ON co2.tableid = t2.tableid
JOIN sys.syskeys k ON co2.constraintid = k.constraintid
JOIN sys.sysconglomerates cg2 ON k.conglomerateid = cg2.conglomerateid
WHERE co.type = 'F' 
    and sc.schemaname = current schema    

the two descriptor entries contain a list of column numbers for each table, like

BTREE(2,1)

where the numbers correspond to the column numbers in the syscolumns table for the corresponding table.

If anyone has an elegant way of extracting this in this query, I would like to know. I am getting a list of all the columns for a table in a separate query and extracting the names from that after parsing the descriptors to get the numbers.

like image 27
johnk Avatar answered Oct 21 '22 06:10

johnk