package fr.pandacube.lib.db; import fr.pandacube.lib.util.Log; /** * A foreign key field in a SQL table. * @param the table class of this current foreign key field * @param the Java type of this field * @param

the table class of the targeted primary key */ public class SQLFKField, T, P extends SQLElement

> extends SQLField { private SQLField sqlPrimaryKeyField; private Class

sqlForeignKeyElemClass; /* package */ SQLFKField(SQLType t, boolean nul, T deflt, Class

fkEl, SQLField fkF) { super(t, nul, deflt); construct(fkEl, fkF); } /* package */ static , F extends SQLElement> SQLFKField idFK(boolean nul, Class fkEl) { return idFK(nul, null, fkEl); } /* package */ static , F extends SQLElement> SQLFKField idFK(boolean nul, Integer deflt, Class fkEl) { if (fkEl == null) throw new IllegalArgumentException("foreignKeyElement can't be null"); try { SQLField f = DB.getSQLIdField(fkEl); return new SQLFKField<>(f.type, nul, deflt, fkEl, f); } catch (DBInitTableException e) { Log.severe("Can't create Foreign key Field targeting id field of '"+fkEl+"'", e); return null; } } /* package */ static , T, F extends SQLElement> SQLFKField customFK(boolean nul, Class fkEl, SQLField fkF) { return customFK(nul, null, fkEl, fkF); } /* package */ static , T, F extends SQLElement> SQLFKField customFK(boolean nul, T deflt, Class fkEl, SQLField fkF) { if (fkEl == null) throw new IllegalArgumentException("foreignKeyElement can't be null"); return new SQLFKField<>(fkF.type, nul, deflt, fkEl, fkF); } private void construct(Class

fkEl, SQLField fkF) { if (fkF == null) throw new IllegalArgumentException("foreignKeyField can't be null"); try { DB.initTable(fkEl); } catch (DBInitTableException e) { throw new RuntimeException(e); } if (fkF.getSQLElementType() == null) throw new RuntimeException("Can't initialize foreign key. The primary key in the table " + fkEl.getName() + " is not properly initialized and can't be targeted by a foreign key"); sqlPrimaryKeyField = fkF; sqlForeignKeyElemClass = fkEl; } /** * Gets the targeted field of this foreign key. * @return the targeted field of this foreign key. */ public SQLField getPrimaryField() { return sqlPrimaryKeyField; } /** * Gets the type of the table containing the targeted field of this foreign key. * @return the type of the table containing the targeted field of this foreign key. */ public Class

getForeignElementClass() { return sqlForeignKeyElemClass; } }