Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat : Foreign key feature in ToolJet database #9544

Merged
merged 163 commits into from
May 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
163 commits
Select commit Hold shift + click to select a range
0e09e1c
feat: added support for creating primarykey and unique constraint whi…
ganesh8056 Mar 19, 2024
59308d0
feat : primary key with unique constraint
S-Abdul-Rahman Mar 19, 2024
6db9ea4
feat : able to create primary key on table creation
S-Abdul-Rahman Mar 20, 2024
f276f17
minor changes for backend
S-Abdul-Rahman Mar 20, 2024
d3e8a8d
checked and added constraints for primary key
S-Abdul-Rahman Mar 20, 2024
4d11a1c
Added tooltips for primary key columns and added a fix for autofocus …
S-Abdul-Rahman Mar 20, 2024
235ec35
Added a new component named TableSchema so that we can use this same …
S-Abdul-Rahman Mar 20, 2024
538898c
fix: fetching tjdb table metadata query has been updated to support u…
ganesh8056 Mar 20, 2024
7f7a4da
Merge branch 'feature/tjdb-create-primarykey' of https://github.com/t…
ganesh8056 Mar 20, 2024
c73c50e
feat : primary key in edit table
S-Abdul-Rahman Mar 21, 2024
866e5ed
mariadb library update
ganesh8056 Mar 21, 2024
d0e7682
Merge branch 'feature/tjdb-create-primarykey' of https://github.com/t…
ganesh8056 Mar 21, 2024
99e241d
atleast one primarky should be mandatory for each field
S-Abdul-Rahman Mar 22, 2024
e16b3cc
Merge branch 'feature/tjdb-create-primarykey' into feature/tjdb-creat…
S-Abdul-Rahman Mar 22, 2024
480bfec
fix: list tjdb table data api due to id column sort by default
ganesh8056 Mar 22, 2024
c261a3e
fix: tjdb dashboard table column datatype icon and name was missing w…
ganesh8056 Mar 25, 2024
3710c49
fix: tjdb create row operation made compatible with Primary key
ganesh8056 Mar 25, 2024
80c0fcd
fix: add column operation will now suport serail and unique constraint
ganesh8056 Mar 26, 2024
0009199
fix: Edit column operation support unique constraints
ganesh8056 Mar 26, 2024
5f09422
fix: added primary key icon is tjdb dashboard table
ganesh8056 Mar 26, 2024
ea3fb7a
feat : foreign key drawer ui
S-Abdul-Rahman Mar 26, 2024
1394cdf
fix: dynamic tooltip text in table for serial datatype and primarykey
ganesh8056 Mar 26, 2024
029f27b
fix: cell edit menu should not open for primary key column and serial…
ganesh8056 Mar 26, 2024
ca6aa45
fix: cell edit menu save flow and boolean toggle update flow will now…
ganesh8056 Mar 26, 2024
d9c5b7f
minor ui change in nested drawer for foreign key relation
S-Abdul-Rahman Mar 27, 2024
eb663a8
fix: edit row operation now supports and works based on primary key f…
ganesh8056 Mar 27, 2024
36a50f4
fix: add row operation refetch query works based on primary key
ganesh8056 Mar 27, 2024
98fd960
Added foreign key active state icon
S-Abdul-Rahman Mar 28, 2024
5189cd0
feat: API to edit table schema
ganesh8056 Mar 28, 2024
f7a53b4
Added fixes for primary constraints
S-Abdul-Rahman Mar 29, 2024
aee9a15
fix: edit table allows to add new columns and delete old columns as well
ganesh8056 Mar 29, 2024
830eb45
Merge branch 'feature/tjdb-create-primarykey' of https://github.com/t…
ganesh8056 Mar 29, 2024
7a75d58
fixes related to primary key
S-Abdul-Rahman Apr 1, 2024
c3d5b2d
fix: primary key mandatory check on edit table API
ganesh8056 Apr 1, 2024
3a1963b
fix: moved table rename inside db transaction
ganesh8056 Apr 1, 2024
30e83e3
fix: on editing a primary key column it will not remove primary key c…
ganesh8056 Apr 1, 2024
23986ab
changes and fixes in primary key integration
S-Abdul-Rahman Apr 2, 2024
ccd8984
edit table api integration
S-Abdul-Rahman Apr 2, 2024
aa8772b
fix: primary key mandatory validation was wrongly placed in edit tabl…
ganesh8056 Apr 3, 2024
3fef516
fix: edit tooljetdb table dto validation modified
ganesh8056 Apr 3, 2024
ab5d022
edit table api integration
S-Abdul-Rahman Apr 3, 2024
d0e9a69
edit table success toast update message
S-Abdul-Rahman Apr 3, 2024
2a3b823
Added tooltip for serial datatype defaultvalue and design change of A…
S-Abdul-Rahman Apr 3, 2024
024378b
Merge branch 'feature/tjdb-create-primarykey' into feature/tjdb-creat…
ganesh8056 Apr 4, 2024
ed0da14
added scrollbar to tableschema and added a hover effect to column whi…
S-Abdul-Rahman Apr 5, 2024
70c28fe
feat: Foreign key creation support in create table Inprogress
ganesh8056 Apr 5, 2024
7e869f9
Merge branch 'feature/tjdb-create-foreignkey' of https://github.com/t…
ganesh8056 Apr 5, 2024
3dda827
fix: code review comments for backend fix inprogress
ganesh8056 Apr 5, 2024
4216274
fix: in edit table operation in tooljetdb for serial datatype default…
ganesh8056 Apr 8, 2024
f79a212
fix: edit table payload naming convention changed
ganesh8056 Apr 8, 2024
b617afc
fix : review comments and ui fixes
S-Abdul-Rahman Apr 8, 2024
d8c2ae7
fix : undefined check error in renameTable function
S-Abdul-Rahman Apr 8, 2024
19fddf5
fix: unique constraint will be false by default on version less than …
ganesh8056 Apr 8, 2024
8504bd4
added primary key icon in edit column header
S-Abdul-Rahman Apr 8, 2024
9539e52
fix: unable to change single primary key to composite primary key whe…
ganesh8056 Apr 8, 2024
50c2e50
Merge branch 'feature/tjdb-create-primarykey' of https://github.com/t…
ganesh8056 Apr 8, 2024
dcf1c57
added regex check for serial datatype's default value
S-Abdul-Rahman Apr 9, 2024
56d2f61
feat : in edit table the primary columns should be group together and…
S-Abdul-Rahman Apr 9, 2024
5b2abf9
fix: custom exception filter for tooljetdb and optimized cell edit sa…
ganesh8056 Apr 10, 2024
2bbab55
Merge branch 'feature/tjdb-create-primarykey' of https://github.com/t…
ganesh8056 Apr 10, 2024
a9bb1c9
fix: primarykey column default value of character varying datatype is…
ganesh8056 Apr 11, 2024
fb5be7f
fix: tjdb exception filter is added at controller level and it can gr…
ganesh8056 Apr 11, 2024
84045ac
fix: on a exception postgrest error message has been sent as response
ganesh8056 Apr 11, 2024
d29bf6f
fix: edit-table api payload details were mis-matching
ganesh8056 Apr 11, 2024
e3798c0
fix: on editing serial datatype column default value is not necessary
ganesh8056 Apr 11, 2024
57880f3
fix: in create and edit table drawer datatype dropdown selection was…
ganesh8056 Apr 11, 2024
a547163
fix: multiple exceptions can be handled together
ganesh8056 Apr 12, 2024
c5f500f
removed the code comments
ganesh8056 Apr 12, 2024
f86ec99
fix : primary key columns should in top of the order in edit table an…
S-Abdul-Rahman Apr 12, 2024
82dcbc0
revert back the changes of primary key column group together in edit …
S-Abdul-Rahman Apr 12, 2024
b9ace34
Add null value for default value when we change the datatype in edit …
S-Abdul-Rahman Apr 12, 2024
dc939a3
Merge branch 'feature/tjdb-create-primarykey' into feature/tjdb-creat…
ganesh8056 Apr 12, 2024
400d53e
Merge branch 'feature/tjdb-create-primarykey' into feature/tjdb-creat…
ganesh8056 Apr 12, 2024
eb4a336
fix: feature to create foreign key while creating a new table
ganesh8056 Apr 15, 2024
bd78b08
integrated source table details and source column details
S-Abdul-Rahman Apr 16, 2024
0f854bb
fix : serial data type cause error in default value when there is mor…
S-Abdul-Rahman Apr 16, 2024
9454b0c
Merge branch 'feature/tjdb-create-primarykey' into feature/tjdb-creat…
ganesh8056 Apr 17, 2024
b549674
Merge branch 'feature/tjdb-create-foreignkey' of https://github.com/t…
ganesh8056 Apr 17, 2024
a85a888
feat: tooljet database table metadata api now includes foreign key de…
ganesh8056 Apr 17, 2024
622521a
feat : foreign key designs for create and edit table
S-Abdul-Rahman Apr 18, 2024
0fb5b8b
fix : view table api error issue
S-Abdul-Rahman Apr 18, 2024
22d2813
feat : foreign key designs for create and edit column
S-Abdul-Rahman Apr 18, 2024
a2075aa
feat: added support for creating foreign key in add column api
ganesh8056 Apr 18, 2024
8d6b4d3
Merge branch 'feature/tjdb-create-foreignkey' of https://github.com/t…
ganesh8056 Apr 18, 2024
f1e2ed4
feat: api to create edit and delete foreign key has been added to too…
ganesh8056 Apr 19, 2024
35ca144
feat : foreign key designs in create and edit row as well as cell edi…
S-Abdul-Rahman Apr 22, 2024
051c688
resolved conflicts
S-Abdul-Rahman Apr 22, 2024
f0f4cd6
resolved conflicts
S-Abdul-Rahman Apr 22, 2024
a28d135
fix : cell click issue in cell edit for boolean type
S-Abdul-Rahman Apr 22, 2024
b249002
feat: added support to select specific columns in the postgrest query
ganesh8056 Apr 22, 2024
e1634aa
Merge branch 'feature/tjdb-create-foreignkey' of https://github.com/t…
ganesh8056 Apr 22, 2024
15329f0
feat: added foreign key referenced table id in metadata details
ganesh8056 Apr 22, 2024
fe1cfd5
fix: naming convention changed for foriegn key apis
ganesh8056 Apr 23, 2024
2a5d293
fix: updated DTO to check on-delete and on-update operation of foreig…
ganesh8056 Apr 24, 2024
155c59c
completed api integration and remaining ui popups for delete and chan…
S-Abdul-Rahman Apr 24, 2024
a5bcd83
added routing logic for navigate to reference table from source table
S-Abdul-Rahman Apr 24, 2024
f8a22ee
implemented infinite scroll logic for cell edit foreign key column va…
S-Abdul-Rahman Apr 25, 2024
f102563
moved scroll logic to selectBox component
S-Abdul-Rahman Apr 25, 2024
c6d2dab
fix: removed the scroll for column schema section in create and edit …
ganesh8056 Apr 25, 2024
484fe4b
fix : major bugs
S-Abdul-Rahman Apr 26, 2024
f01deb2
fix: added support to delete FK in Edit Column API
ganesh8056 Apr 26, 2024
3e16287
feat: Join FK columns auto populate on query manager
ganesh8056 Apr 28, 2024
c8cad3c
feat : allowing to create multiple foreign keys in single table
S-Abdul-Rahman Apr 29, 2024
622e11b
feat: auto suggestion on joins
ganesh8056 Apr 29, 2024
ba59be2
fix: foreign key column must be rearranged to top of the list
ganesh8056 Apr 29, 2024
ef8bc27
fix : major bugs
S-Abdul-Rahman Apr 29, 2024
b93fcb2
fix : bugs list
S-Abdul-Rahman Apr 29, 2024
60e04fb
fix: foreignkey details on tjdb context were not updated properly
ganesh8056 Apr 29, 2024
5f7bd3b
Merge branch 'feature/tjdb-create-foreignkey' of https://github.com/t…
ganesh8056 Apr 29, 2024
1eb2917
fix : bugs in calling selectQuery api
S-Abdul-Rahman Apr 29, 2024
0aec3e5
completed missed routing logic in cell edit dropdown
S-Abdul-Rahman Apr 29, 2024
882a412
fix: cell edit menu on clicking search closes
ganesh8056 Apr 30, 2024
87129a1
fix : bugs list
S-Abdul-Rahman Apr 30, 2024
873823d
fix: cellEdit drop down menu provides wrong values for FK
ganesh8056 Apr 30, 2024
da42093
Merge branch 'feature/tjdb-create-foreignkey' of https://github.com/t…
ganesh8056 Apr 30, 2024
ffe3334
fix: fk values is made to default onClosing CellEditMenu
ganesh8056 Apr 30, 2024
4c9530f
fix: on table cell click foreign key details are made to default state
ganesh8056 Apr 30, 2024
6107ead
fix : bugs in edit row and in all dropdown which is showing reference…
S-Abdul-Rahman Apr 30, 2024
474fa76
fix: infinite scroll for listing foreign key drop down
ganesh8056 Apr 30, 2024
c7910f1
Merge branch 'feature/tjdb-create-foreignkey' of https://github.com/t…
ganesh8056 Apr 30, 2024
9983cba
fix: infinite scroll in FK data dropdown goes unresponsive
ganesh8056 Apr 30, 2024
fae99d0
fix : width of tooltip in showing foreign key relation and throwing e…
S-Abdul-Rahman May 1, 2024
e7db8bd
fix : the search api needs to hit only for the referenced column name…
S-Abdul-Rahman May 1, 2024
11b3a43
fix: basic lint fixes
ganesh8056 May 1, 2024
12d64bb
fix : default value preselect value is passing as empty in create row…
S-Abdul-Rahman May 1, 2024
ebc90b3
fix : create row sort logic and fix for edit foreign key relation
S-Abdul-Rahman May 2, 2024
550a734
solved merge conflict
S-Abdul-Rahman May 2, 2024
a0ad113
fix : merge conflict stylings collapsed
S-Abdul-Rahman May 2, 2024
29dfb2a
feat: implemented infinite scrolling for listing down FK data in cell…
ganesh8056 May 2, 2024
e179720
Merge branch 'feature/tjdb-create-foreignkey' of https://github.com/t…
ganesh8056 May 2, 2024
609d5bb
fix: in edit column while we create a new foreign key it was not refl…
ganesh8056 May 2, 2024
67e6df3
fix: join query when auto populated with columns table name was missing
ganesh8056 May 3, 2024
6c13d30
fix: Not able to edit a table when a column has been referenced for f…
ganesh8056 May 3, 2024
e32c0dc
fix: serial data-type column will have placeholder as auto-generated
ganesh8056 May 4, 2024
3614576
fix : bugs from design review
S-Abdul-Rahman May 6, 2024
bb1aa31
fix : icon mismatch in source and target column
S-Abdul-Rahman May 6, 2024
b786811
Feature: Import Export revison for TJDB relations (#9597)
akshaysasidrn May 6, 2024
10bd1f9
fix: cell edit drop down search issue and drop down misses the values…
ganesh8056 May 6, 2024
f586a34
Merge branch 'feature/tjdb-create-foreignkey' of https://github.com/t…
ganesh8056 May 6, 2024
a64c0b8
fix : disabling serial type in source column and removing strict rul…
S-Abdul-Rahman May 6, 2024
dba6f75
fix : validation issue for save changes button in foreign key drawer
S-Abdul-Rahman May 6, 2024
28e5f79
disabled creation of foreign key from create and edit column and enab…
S-Abdul-Rahman May 6, 2024
361286f
fix : edit column foreign key relation is becomes false when we close…
S-Abdul-Rahman May 6, 2024
1ec08fb
fix: composite primary key columns cannot be mapped to foreign key
ganesh8056 May 6, 2024
0b5a368
fix : create column and edit column : previous column values are popu…
S-Abdul-Rahman May 6, 2024
97f1949
fix : Unable to see the column menu icon when column name has 32 char…
S-Abdul-Rahman May 7, 2024
f72d012
Merge branch 'release/database-1.1' into feature/tjdb-create-foreignkey
akshaysasidrn May 7, 2024
dcee602
fix : edit column delete is not working when we chnage the foreign ke…
S-Abdul-Rahman May 7, 2024
da24ef0
fix bulk upload for case sensitive columns
akshaysasidrn May 7, 2024
1ad591c
fix : while selecting different table in target table, the target col…
S-Abdul-Rahman May 7, 2024
cfe980b
Fix : Bugs from Foreign key feature (#9552)
manishkushare May 7, 2024
1f64a3f
Merge branch 'release/database-1.1' into feature/tjdb-create-foreignkey
akshaysasidrn May 7, 2024
74c5594
fix: When we create a FK relation, and then if we change a source col…
ganesh8056 May 7, 2024
622ed2f
Merge branch 'feature/tjdb-create-foreignkey' of https://github.com/t…
ganesh8056 May 7, 2024
9f10ee6
Feature: Add setup to standardise TJDB error handling (#9629)
akshaysasidrn May 7, 2024
188bd1f
fix: add column api dto validation updated
ganesh8056 May 7, 2024
fb1f51c
Merge branch 'feature/tjdb-create-foreignkey' of https://github.com/t…
ganesh8056 May 7, 2024
5eca563
return records to throw errors from postgrest
akshaysasidrn May 7, 2024
390f3d7
fix type
akshaysasidrn May 7, 2024
1e15c96
Chore: Primary key backward compatibility migration (#9636)
akshaysasidrn May 8, 2024
66fe6e0
handle unique name error on table create
akshaysasidrn May 8, 2024
a6fb2f2
Fix : Bug fixes from foreign key feature (#9637)
manishkushare May 8, 2024
8e703f6
fix : placeholder text in foreign key drawer and error handleing text…
S-Abdul-Rahman May 8, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,37 @@ const DropDownSelect = ({
showPlaceHolder = false,
highlightSelected = true,
buttonClasses = '',
foreignKeyAccess = false,
showRedirection = false,
columnInfoForTable,
showColumnInfo = false,
showDescription = false,
foreignKeyAccessInRowForm = false,
topPlaceHolder = '',
showPlaceHolderInForeignKeyDrawer = false,
isCellEdit = false,
scrollEventForColumnValus,
organizationId,
foreignKeys,
setReferencedColumnDetails,
shouldShowForeignKeyIcon = false,
cellColumnName,
tableName,
targetTable,
actions,
actionName,
fetchTables,
onTableClick,
}) => {
const popoverId = useRef(`dd-select-${uuidv4()}`);
const popoverBtnId = useRef(`dd-select-btn-${uuidv4()}`);
const [showMenu, setShowMenu] = useShowPopover(false, `#${popoverId.current}`, `#${popoverBtnId.current}`);
const [selected, setSelected] = useState(value);
const selectRef = useRef();
const [isOverflown, setIsOverflown] = useState(false);
// Applicable when drop down is used to list FK data
const [isInitialForeignKeyDataLoaded, setIsInitialForeignKeyDataLoaded] = useState(false);
const [totalRecords, setTotalRecords] = useState(0);
const [pageNumber, setPageNumber] = useState(1);

useEffect(() => {
if (showMenu) {
Expand All @@ -42,6 +66,7 @@ const DropDownSelect = ({
if (Array.isArray(value) || selected?.value !== value?.value || selected?.label !== value?.label) {
setSelected(value);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [value]);

useEffect(() => {
Expand All @@ -61,6 +86,7 @@ const DropDownSelect = ({
if (isNewOverFlown !== isOverflown) {
setIsOverflown(isNewOverFlown);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selected]);

function checkElementPosition() {
Expand All @@ -70,14 +96,9 @@ const DropDownSelect = ({
}

const elementRect = selectControl.getBoundingClientRect();

// Check proximity to top
const halfScreenHeight = window.innerHeight / 2;

if (elementRect.top <= halfScreenHeight) {
return 'bottom-start';
}

if (elementRect.top <= halfScreenHeight) return 'bottom-start';
return 'top-start';
}

Expand All @@ -98,17 +119,26 @@ const DropDownSelect = ({
<OverlayTrigger
show={showMenu && !disabled}
placement={checkElementPosition()}
// placement="auto"
// arrowOffsetTop={90}
// arrowOffsetLeft={90}
overlay={
<Popover
key={'page.i'}
id={popoverId.current}
className={`${darkMode && 'popover-dark-themed dark-theme tj-dark-mode'}`}
style={{
width: '244px',
maxWidth: '246px',
width: foreignKeyAccess
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

prefer using classnames

? '403px'
: foreignKeyAccessInRowForm === true
? '494px'
: isCellEdit
? '266px'
: '244px',
maxWidth: foreignKeyAccess
? '403px'
: foreignKeyAccessInRowForm === true
? '494px'
: isCellEdit
? '266px'
: '246px',
overflow: 'hidden',
boxShadow: '0px 2px 4px -2px rgba(16, 24, 40, 0.06), 0px 4px 8px -2px rgba(16, 24, 40, 0.10)',
}}
Expand All @@ -127,6 +157,29 @@ const DropDownSelect = ({
addBtnLabel={addBtnLabel}
emptyError={emptyError}
highlightSelected={highlightSelected}
foreignKeyAccess={foreignKeyAccess}
showRedirection={showRedirection}
columnInfoForTable={columnInfoForTable}
showColumnInfo={showColumnInfo}
showDescription={showDescription}
foreignKeyAccessInRowForm={foreignKeyAccessInRowForm}
isCellEdit={isCellEdit}
scrollEventForColumnValus={scrollEventForColumnValus}
organizationId={organizationId}
foreignKeys={foreignKeys}
setReferencedColumnDetails={setReferencedColumnDetails}
shouldShowForeignKeyIcon={shouldShowForeignKeyIcon}
cellColumnName={cellColumnName}
isInitialForeignKeyDataLoaded={isInitialForeignKeyDataLoaded}
setIsInitialForeignKeyDataLoaded={setIsInitialForeignKeyDataLoaded}
totalRecords={totalRecords}
setTotalRecords={setTotalRecords}
pageNumber={pageNumber}
setPageNumber={setPageNumber}
Comment on lines +160 to +178
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm concerned about the number of props piling up, can we group them based on context to have better readability?

pagination={{
  pageNumber,
  setPageNumber,
  totalRecords,
  setTotalRecords
}}

foreignKeyProps={{
  foreignKeyAccess,
  foreignKeyAccessInRowForm,
  foreignKeys,
  setReferencedColumnDetails,
  shouldShowForeignKeyIcon,
  isInitialForeignKeyDataLoaded,
  setIsInitialForeignKeyDataLoaded
}}

tableName={tableName}
targetTable={targetTable}
actions={actions}
actionName={actionName}
/>
</Popover>
}
Expand All @@ -142,16 +195,19 @@ const DropDownSelect = ({
return;
}
setShowMenu((show) => !show);
if (onTableClick === true) {
fetchTables();
}
}}
className={cx(
{
'justify-content-start': !shouldCenterAlignText,
'justify-content-centre': shouldCenterAlignText,
'border-1 tdb-dropdown-btn-foreignKeyAccess': foreignKeyAccess || foreignKeyAccessInRowForm,
'border-0 tdb-dropdown-btn': !foreignKeyAccess || !foreignKeyAccessInRowForm,
},
'tdb-dropdown-btn',
'gap-0',
'w-100',
'border-0',
'rounded-0',
'position-relative',
'font-weight-normal',
Expand All @@ -176,7 +232,9 @@ const DropDownSelect = ({
selected?.label
)
) : showPlaceHolder ? (
<span style={{ color: '#9e9e9e' }}>Select..</span>
<span style={{ color: '#9e9e9e' }}>
{foreignKeyAccessInRowForm || showPlaceHolderInForeignKeyDrawer ? topPlaceHolder : 'Select...'}
</span>
) : (
''
)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ import { useNavigate } from 'react-router-dom';
import useConfirm from './Confirm';

const JoinConstraint = ({ darkMode, index, onRemove, onChange, data }) => {
const { selectedTableId, tables, joinOptions, findTableDetails } = useContext(TooljetDatabaseContext);
const { selectedTableId, tables, joinOptions, findTableDetails, tableForeignKeyInfo } =
useContext(TooljetDatabaseContext);
const joinType = data?.joinType;
const baseTableDetails = (selectedTableId && findTableDetails(selectedTableId)) || {};
const conditionsList = isEmpty(data?.conditions?.conditionsList) ? [{}] : data?.conditions?.conditionsList;
Expand Down Expand Up @@ -45,19 +46,150 @@ const JoinConstraint = ({ darkMode, index, onRemove, onChange, data }) => {
});
tableSet.add(selectedTableId);

const leftTableList = [...tableSet]
// In Joins-Query, the table on the LHS should be the ones which we already selected for base table or the tables which we selected on RHS
const leftTableList = [];
[...tableSet]
.filter((table) => table !== rightFieldTable)
.map((t) => {
.forEach((t) => {
const tableDetails = findTableDetails(t);
return { label: tableDetails?.table_name ?? '', value: t };
const targetTableFKListWithAdjacentTable = checkIfAdjacentTableHasForeignKey(true, t?.table_id);
if (targetTableFKListWithAdjacentTable.length) {
leftTableList.unshift({
label: tableDetails?.table_name ?? '',
value: t,
isTargetTable: !!targetTableFKListWithAdjacentTable.length,
});
} else {
leftTableList.push({
label: tableDetails?.table_name ?? '',
value: t,
isTargetTable: !!targetTableFKListWithAdjacentTable.length,
});
}
});

const tableList = tables
// Tables to list on Right-Hand-Side of Join operation, Omits already selected table
const tableList = [];
tables
.filter((table) => ![...tableSet, leftFieldTable].includes(table.table_id))
.map((t) => {
return { label: t?.table_name ?? '', value: t.table_id };
.forEach((t) => {
const targetTableFKListWithAdjacentTable = checkIfAdjacentTableHasForeignKey(false, t?.table_id);
if (targetTableFKListWithAdjacentTable.length) {
tableList.unshift({
label: t?.table_name ?? '',
value: t?.table_id,
isTargetTable: !!targetTableFKListWithAdjacentTable.length,
});
} else {
tableList.push({
label: t?.table_name ?? '',
value: t?.table_id,
isTargetTable: !!targetTableFKListWithAdjacentTable.length,
});
}
});

// OnSelecting LHS ro RHS table on Join Operation, Checking if Adjacent table has FK relation and Auto Fill the column values
function checkIfAdjacentTableHasForeignKey(isChoosingLHStable, tableId) {
if (isChoosingLHStable && rightFieldTable) {
const rightFieldTableDetails = findTableDetails(rightFieldTable);
if (rightFieldTableDetails?.table_name && tableForeignKeyInfo[rightFieldTableDetails.table_name]) {
return tableForeignKeyInfo[rightFieldTableDetails.table_name].filter(
(foreignKeyDetail) => foreignKeyDetail.referenced_table_id === tableId
);
}
}

if (!isChoosingLHStable && leftFieldTable) {
const leftFieldTableTableDetails = findTableDetails(leftFieldTable);
if (leftFieldTableTableDetails?.table_name && tableForeignKeyInfo[leftFieldTableTableDetails.table_name]) {
return tableForeignKeyInfo[leftFieldTableTableDetails.table_name].filter(
(foreignKeyDetail) => foreignKeyDetail.referenced_table_id === tableId
);
}
}

return [];
}

function autoFillColumnIfForeignKeyExists(tableId, isChoosingLHStable) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nicely done!

const adjacentTableForeignKeyDetails = checkIfAdjacentTableHasForeignKey(isChoosingLHStable, tableId);
if (isChoosingLHStable) {
if (adjacentTableForeignKeyDetails.length) {
const newData = cloneDeep({ ...data });
const newConditionsList = adjacentTableForeignKeyDetails.map((adjacentTableForeignKey) => {
const { referenced_column_names = [], column_names = [] } = adjacentTableForeignKey;
const newCondition = {
leftField: {
table: tableId,
type: 'Column',
...(referenced_column_names[0] && { columnName: referenced_column_names[0] }),
},
operator: '=',
rightField: {
table: rightFieldTable,
type: 'Column',
...(column_names[0] && { columnName: column_names[0] }),
},
};

return newCondition;
});
set(newData, 'conditions.conditionsList', newConditionsList);
onChange(newData);
} else {
const newData = cloneDeep({ ...data });
const { conditionsList = [{}] } = newData?.conditions || {};
const newConditionsList = conditionsList.map((condition) => {
const newCondition = { ...condition };
set(newCondition, 'leftField.table', tableId);
set(newCondition, 'operator', '='); //should we removed when we have more options
return newCondition;
});
set(newData, 'conditions.conditionsList', newConditionsList);
// set(newData, 'table', value?.value);
onChange(newData);
}
} else {
if (adjacentTableForeignKeyDetails.length) {
const newData = cloneDeep({ ...data });
const newConditionsList = adjacentTableForeignKeyDetails.map((adjacentTableForeignKey) => {
const { referenced_column_names = [], column_names = [] } = adjacentTableForeignKey;
const newCondition = {
leftField: {
table: leftFieldTable,
type: 'Column',
...(column_names[0] && { columnName: column_names[0] }),
},
operator: '=',
rightField: {
table: tableId,
type: 'Column',
...(referenced_column_names[0] && { columnName: referenced_column_names[0] }),
},
};

return newCondition;
});
set(newData, 'conditions.conditionsList', newConditionsList);
set(newData, 'table', tableId);
onChange(newData);
} else {
const newData = cloneDeep({ ...data });
const { conditionsList = [] } = newData?.conditions || {};
const newConditionsList = conditionsList.map((condition) => {
const newCondition = { ...condition };
set(newCondition, 'rightField.table', tableId);
set(newCondition, 'operator', '='); //should we removed when we have more options
return newCondition;
});
set(newData, 'conditions.conditionsList', newConditionsList);
set(newData, 'table', tableId);
onChange(newData);
}
}
}

return (
<Container fluid className="p-0">
<Row className={`mx-0 ${index === 0 && 'pb-2'}`}>
Expand Down Expand Up @@ -118,23 +250,12 @@ const JoinConstraint = ({ darkMode, index, onRemove, onChange, data }) => {
result = true;
}

if (result) {
const newData = cloneDeep({ ...data });
const { conditionsList = [{}] } = newData?.conditions || {};
const newConditionsList = conditionsList.map((condition) => {
const newCondition = { ...condition };
set(newCondition, 'leftField.table', value?.value);
set(newCondition, 'operator', '='); //should we removed when we have more options
return newCondition;
});
set(newData, 'conditions.conditionsList', newConditionsList);
// set(newData, 'table', value?.value);
onChange(newData);
}
if (result) autoFillColumnIfForeignKeyExists(value?.value, true);
}}
onAdd={() => navigate(getPrivateRoute('database'))}
addBtnLabel={'Add new table'}
value={leftTableList.find((val) => val?.value === leftFieldTable)}
shouldShowForeignKeyIcon
/>
) : (
<div
Expand Down Expand Up @@ -182,23 +303,12 @@ const JoinConstraint = ({ darkMode, index, onRemove, onChange, data }) => {
);
}

if (result) {
const newData = cloneDeep({ ...data });
const { conditionsList = [] } = newData?.conditions || {};
const newConditionsList = conditionsList.map((condition) => {
const newCondition = { ...condition };
set(newCondition, 'rightField.table', value?.value);
set(newCondition, 'operator', '='); //should we removed when we have more options
return newCondition;
});
set(newData, 'conditions.conditionsList', newConditionsList);
set(newData, 'table', value?.value);
onChange(newData);
}
if (result) autoFillColumnIfForeignKeyExists(value?.value, false);
}}
onAdd={() => navigate(getPrivateRoute('database'))}
addBtnLabel={'Add new table'}
value={tableList.find((val) => val?.value === rightFieldTable)}
shouldShowForeignKeyIcon
/>
</Col>
</Row>
Expand Down