Browse Source

feat: Add hasMany UI cell

Signed-off-by: Pranav C Balan <pranavxc@gmail.com>
pull/341/head
Pranav C Balan 4 years ago committed by Pranav C
parent
commit
05369f46ef
  1. 5
      README.md
  2. 6
      packages/nc-gui/components/project/spreadsheet/editColumn/editColumn.vue
  3. 262
      packages/nc-gui/components/project/spreadsheet/editColumn/linkedToAnotherOptions.vue
  4. 288
      packages/nc-gui/components/project/spreadsheet/editableCell/hasManyCell.vue
  5. 8
      packages/nc-gui/components/project/spreadsheet/helpers/uiTypes.js
  6. 1
      packages/nc-gui/components/project/spreadsheet/rowsXcDataTable.vue
  7. 47
      packages/nc-gui/components/project/spreadsheet/views/xcGridView.vue
  8. 17
      packages/nocodb/src/lib/noco/common/BaseApiBuilder.ts
  9. 5
      packages/nocodb/src/lib/noco/common/XcMigrationSource.ts
  10. 85
      packages/nocodb/src/lib/noco/gql/GqlApiBuilder.ts
  11. 43
      packages/nocodb/src/lib/noco/migrations/nc_002_add_m2m.ts

5
README.md

@ -244,6 +244,9 @@ Our mission is to provide the most powerful no-code interface for databases whic
* Create a new relation * Create a new relation
- Create foreign key in child table - Create foreign key in child table
- Update metadata - Update metadata
- GUI
-
* Existing * Existing
- We need to show existing relation - We need to show existing relation
- Update metadata - Update metadata
@ -259,4 +262,6 @@ Our mission is to provide the most powerful no-code interface for databases whic
* Pagination * Pagination
* Remove child * Remove child

6
packages/nc-gui/components/project/spreadsheet/editColumn/editColumn.vue

@ -319,7 +319,6 @@ export default {
value: Boolean value: Boolean
}, },
data: () => ({ data: () => ({
valid: false,
relationDeleteDlg: false, relationDeleteDlg: false,
newColumn: {}, newColumn: {},
uiTypes, uiTypes,
@ -495,10 +494,7 @@ export default {
}, },
computed: { computed: {
isEditDisabled() { isEditDisabled() {
return this.editColumn && this.isSQLite && !this.relation; return this.editColumn && this.sqlUi === SqliteUi;
},
isSQLite() {
return this.sqlUi === SqliteUi
}, },
dataTypes() { dataTypes() {
return this.sqlUi.getDataTypeListForUiType(this.newColumn) return this.sqlUi.getDataTypeListForUiType(this.newColumn)

262
packages/nc-gui/components/project/spreadsheet/editColumn/linkedToAnotherOptions.vue

@ -1,101 +1,111 @@
<template> <template>
<v-container fluid class="wrapper"> <div>
<v-row> <v-container fluid class="wrapper mb-3">
<v-col cols="6"> <v-row>
<v-autocomplete <v-col>
outlined <v-radio-group row hide-details dense v-model="type" class="pt-0 mt-0">
class="caption" <v-radio value="hm" label="Has Many"></v-radio>
hide-details <v-radio disabled value="mm" label="Many To Many"></v-radio>
:loading="isRefTablesLoading" <v-radio disabled value="oo" label="One To One"></v-radio>
label="Reference Table" </v-radio-group>
:full-width="false" </v-col>
v-model="relation.parentTable" </v-row>
:items="refTables" </v-container>
item-text="_tn"
item-value="tn" <v-container fluid class="wrapper">
required <v-row>
dense <v-col cols="6">
@change="loadColumnList" <v-autocomplete
></v-autocomplete> outlined
</v-col class="caption"
> hide-details
<v-col cols="6"> :loading="isRefTablesLoading"
<v-autocomplete label="Child Table"
outlined :full-width="false"
class="caption" v-model="relation.childTable"
hide-details :items="refTables"
:loading="isRefColumnsLoading" item-text="_tn"
label="Reference Column" item-value="tn"
:full-width="false" required
v-model="relation.parentColumn" dense
:items="refColumns" ></v-autocomplete>
item-text="_cn" </v-col
item-value="cn" >
required <v-col cols="6">
dense <v-text-field
ref="parentColumnRef" outlined
@change="onColumnSelect" class="caption"
></v-autocomplete> hide-details
</v-col label="Child Column"
> :full-width="false"
</v-row> v-model="relation.childColumn"
required
<v-row> dense
<v-col cols="6"> ref="childColumnRef"
<v-autocomplete @change="onColumnSelect"
outlined ></v-text-field>
class="caption" </v-col
hide-details >
label="On Update" </v-row>
:full-width="false"
v-model="relation.onUpdate" <v-row>
:items="onUpdateDeleteOptions" <v-col cols="6">
required <v-autocomplete
dense outlined
:disabled="relation.type !== 'real'" class="caption"
></v-autocomplete> hide-details
</v-col> label="On Update"
<v-col cols="6"> :full-width="false"
<v-autocomplete v-model="relation.onUpdate"
outlined :items="onUpdateDeleteOptions"
class="caption" required
hide-details dense
label="On Delete" :disabled="relation.type !== 'real'"
:full-width="false" ></v-autocomplete>
v-model="relation.onDelete" </v-col>
:items="onUpdateDeleteOptions" <v-col cols="6">
required <v-autocomplete
dense outlined
:disabled="relation.type !== 'real'" class="caption"
></v-autocomplete> hide-details
</v-col> label="On Delete"
</v-row> :full-width="false"
v-model="relation.onDelete"
:items="onUpdateDeleteOptions"
<v-row> required
dense
<v-col> :disabled="relation.type !== 'real'"
<v-checkbox ></v-autocomplete>
false-value="real" </v-col>
true-value="virtual" </v-row>
label="Virtual Relation"
:full-width="false"
v-model="relation.type" <v-row>
required
class="mt-0" <v-col>
dense <v-checkbox
></v-checkbox> false-value="real"
</v-col> true-value="virtual"
</v-row> label="Virtual Relation"
:full-width="false"
</v-container> v-model="relation.type"
required
class="mt-0"
dense
></v-checkbox>
</v-col>
</v-row>
</v-container>
</div>
</template> </template>
<script> <script>
export default { export default {
name: "linked-to-another-options", name: "linked-to-another-options",
props: ['nodes', 'column'], props: ['nodes', 'column', 'meta'],
data: () => ({ data: () => ({
type: 'hm',
refTables: [], refTables: [],
refColumns: [], refColumns: [],
relation: {}, relation: {},
@ -112,7 +122,7 @@ export default {
async created() { async created() {
await this.loadTablesList(); await this.loadTablesList();
this.relation = { this.relation = {
childColumn: this.column.cn, childColumn: `${this.meta.tn}_id`,
childTable: this.nodes.tn, childTable: this.nodes.tn,
parentTable: this.column.rtn || "", parentTable: this.column.rtn || "",
parentColumn: this.column.rcn || "", parentColumn: this.column.rcn || "",
@ -124,14 +134,11 @@ export default {
}, },
methods: { methods: {
async loadColumnList() { async loadColumnList() {
if (!this.relation.parentTable) return;
this.isRefColumnsLoading = true; this.isRefColumnsLoading = true;
const result = await this.$store.dispatch('sqlMgr/ActSqlOp', [{ const result = await this.$store.dispatch('sqlMgr/ActSqlOp', [{
env: this.nodes.env, env: this.nodes.env,
dbAlias: this.nodes.dbAlias dbAlias: this.nodes.dbAlias
}, 'columnList', {tn: this.relation.parentTable}]) }, 'columnList', {tn: this.meta.tn}])
const columns = result.data.list; const columns = result.data.list;
@ -160,21 +167,70 @@ export default {
}, 'tableList']); }, 'tableList']);
this.refTables = result.data.list.map(({tn,_tn}) => ({tn,_tn})) this.refTables = result.data.list.map(({tn, _tn}) => ({tn, _tn}))
this.isRefTablesLoading = false; this.isRefTablesLoading = false;
}, },
async saveRelation() { async saveRelation() {
try { try {
let result = await this.$store.dispatch('sqlMgr/ActSqlOpPlus', [ const parentPK = this.meta.columns.find(c => c.pk);
const childTableData = await this.$store.dispatch('sqlMgr/ActSqlOp', [{
env: this.nodes.env,
dbAlias: this.nodes.dbAlias
}, 'tableXcModelGet', {
tn: this.relation.childTable
}]);
const childMeta = JSON.parse(childTableData.meta)
const newChildColumn = {};
Object.assign(newChildColumn, {
cn: this.relation.childColumn,
_cn: this.relation.childColumn,
rqd: false,
pk: false,
ai: false,
cdf: null,
dt: parentPK.dt,
dtxp: parentPK.dtxp,
dtxs: parentPK.dtxs,
un: parentPK.un,
altered: 1
});
const columns = [...childMeta.columns, newChildColumn];
let result = await this.$store.dispatch('sqlMgr/ActSqlOpPlus', [{
env: this.nodes.env,
dbAlias: this.nodes.dbAlias
}, "tableUpdate", {
tn: childMeta.tn,
_tn: childMeta._tn,
originalColumns: childMeta.columns,
columns
}]);
await this.$store.dispatch('sqlMgr/ActSqlOpPlus', [
{ {
env: this.nodes.env, env: this.nodes.env,
dbAlias: this.nodes.dbAlias dbAlias: this.nodes.dbAlias
}, },
this.relation.type === 'real' ? "relationCreate" : 'xcVirtualRelationCreate', this.relation.type === 'real' ? "relationCreate" : 'xcVirtualRelationCreate',
this.relation {
...this.relation,
parentTable: this.meta.tn,
parentColumn: parentPK.cn,
updateRelation: this.column.rtn ? true : false,
type: 'real'
}
]); ]);
} catch (e) { } catch (e) {
throw e; console.log(e.message)
} }
}, },
onColumnSelect() { onColumnSelect() {
@ -182,11 +238,7 @@ export default {
this.$emit('onColumnSelect', col) this.$emit('onColumnSelect', col)
} }
}, },
watch: {
'column.cn': (c) => {
this.$set(this.relation, 'childColumn', c);
}
}
} }
</script> </script>

288
packages/nc-gui/components/project/spreadsheet/editableCell/hasManyCell.vue

@ -0,0 +1,288 @@
<template>
<div class="d-flex">
<div class="d-flex align-center img-container flex-grow-1 hm-items">
<template v-if="value">
<v-chip
small
v-for="(v,i) in value.map(v=>Object.values(v)[1])"
:color="colors[i%colors.length]" :key="j">
{{ v }}
</v-chip>
</template>
</div>
<div class="d-flex align-center justify-center px-1 flex-shrink-1">
<x-icon small :color="['primary','grey']" @click="showNewRecordModal">mdi-plus</x-icon>
<x-icon x-small :color="['primary','grey']" @click="showChildListModal" class="ml-2">mdi-arrow-expand</x-icon>
</div>
<v-dialog v-if="newRecordModal" v-model="newRecordModal" width="600">
<v-card width="600" color="backgroundColor">
<v-card-title class="textColor--text mx-2">Add Record</v-card-title>
<v-card-text>
<v-text-field
hide-details
dense
outlined
placeholder="Search record"
class="mb-2 mx-2 caption"
/>
<div class="items-container">
<template v-if="list">
<v-card
v-for="(ch,i) in list.list"
class="ma-2 child-card"
outlined
v-ripple
@click="addChildToParent(ch)"
:key="i"
>
<v-card-title class="primary-value textColor--text text--lighten-2">{{ ch[childPrimaryCol] }}
<span class="grey--text caption primary-key"
v-if="childPrimaryKey">(Primary Key : {{ ch[childPrimaryKey] }})</span>
</v-card-title>
</v-card>
</template>
</div>
</v-card-text>
<v-card-actions class="justify-center pb-6 ">
<v-btn small outlined class="caption" color="primary">
<v-icon>mdi-plus</v-icon>
Add New Record
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
<v-dialog v-if="childListModal" v-model="childListModal" width="600">
<v-card width="600" color="backgroundColor">
<v-card-title class="textColor--text mx-2">{{ childMeta ? childMeta._tn : 'Children' }}</v-card-title>
<v-card-text>
<div class="items-container">
<template v-if="childList">
<v-card
v-for="(ch,i) in childList.list"
class="ma-2 child-list-modal child-card"
outlined
:key="i"
>
<x-icon
class="remove-child-icon"
:color="['error','grey']"
small
@click="removeChild(ch,i)"
>mdi-delete-outline
</x-icon>
<v-card-title class="primary-value textColor--text text--lighten-2">{{ ch[childPrimaryCol] }}
<span class="grey--text caption primary-key"
v-if="childPrimaryKey">(Primary Key : {{ ch[childPrimaryKey] }})</span>
</v-card-title>
</v-card>
</template>
</div>
</v-card-text>
<v-card-actions class="justify-center pb-6">
<v-btn small outlined class="caption" color="primary" @click="showNewRecordModal">
<v-icon>mdi-plus</v-icon>
Add Record
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
<dlg-label-submit-cancel
type="primary"
v-if="dialogShow"
:actionsMtd="confirmAction"
:dialogShow="dialogShow"
:heading="confirmMessage"
>
</dlg-label-submit-cancel>
</div>
</template>
<script>
import colors from "@/mixins/colors";
import ApiFactory from "@/components/project/spreadsheet/apis/apiFactory";
import DlgLabelSubmitCancel from "@/components/utils/dlgLabelSubmitCancel";
export default {
name: "has-many-cell",
components: {DlgLabelSubmitCancel},
mixins: [colors],
props: {
value: [Object, Array],
meta: [Object],
hm: Object,
nodes: [Object],
row: [Object]
},
data: () => ({
newRecordModal: false,
childListModal: false,
childMeta: null,
list: null,
childList: null,
dialogShow: false,
confirmAction: null,
confirmMessage: ''
}),
methods: {
async showChildListModal() {
this.childListModal = true;
await this.getChildMeta();
const pid = this.meta.columns.filter((c) => c.pk).map(c => this.row[c._cn]).join(',');
const _cn = this.childMeta.columns.find(c => c.cn === this.hm.cn)._cn;
this.childList = await this.childApi.paginatedList({
where: `(${_cn},eq,${pid})`
})
},
async removeChild(child) {
this.dialogShow = true;
this.confirmMessage =
'Do you want to delete the record?';
this.confirmAction = async act => {
if (act === 'hideDialog') {
this.dialogShow = false;
} else {
const id = this.childMeta.columns.filter((c) => c.pk).map(c => child[c._cn]).join(',');
await this.childApi.delete(id)
this.showChildListModal();
this.dialogShow = false;
this.$emit('loadTableData')
}
}
},
async getChildMeta() {
// todo: optimize
if (!this.childMeta) {
const childTableData = await this.$store.dispatch('sqlMgr/ActSqlOp', [{
env: this.nodes.env,
dbAlias: this.nodes.dbAlias
}, 'tableXcModelGet', {
tn: this.hm.tn
}]);
this.childMeta = JSON.parse(childTableData.meta)
}
},
async showNewRecordModal() {
this.newRecordModal = true;
await this.getChildMeta();
this.list = await this.childApi.paginatedList({})
},
async addChildToParent(child) {
const id = this.childMeta.columns.filter((c) => c.pk).map(c => child[c._cn]).join(',');
const pid = this.meta.columns.filter((c) => c.pk).map(c => this.row[c._cn]).join(',');
const _cn = this.childMeta.columns.find(c => c.cn === this.hm.cn)._cn;
this.newRecordModal = false;
await this.childApi.update(id, {
[_cn]: pid
}, {
[_cn]: child[this.childPrimaryKey]
});
this.$emit('loadTableData')
}
},
computed: {
childApi() {
return this.childMeta && this.childMeta._tn ?
ApiFactory.create(this.$store.getters['project/GtrProjectType'],
this.childMeta && this.childMeta._tn, this.childMeta && this.childMeta.columns, this) : null;
},
childPrimaryCol() {
return this.childMeta && (this.childMeta.columns.find(c => c.pv) || {})._cn
},
childPrimaryKey() {
return this.childMeta && (this.childMeta.columns.find(c => c.pk) || {})._cn
}
}
}
</script>
<style scoped lang="scss">
.items-container {
overflow-x: visible;
max-height: min(500px, 60vh);
overflow-y: auto;
}
.primary-value {
.primary-key {
display: none;
margin-left: .5em;
}
&:hover .primary-key {
display: inline;
}
}
.child-list-modal {
position: relative;
.remove-child-icon {
position: absolute;
right: 10px;
top: 10px;
bottom: 10px;
opacity: 0;
}
&:hover .remove-child-icon {
opacity: 1;
}
}
.child-card {
cursor: pointer;
&:hover {
box-shadow: 0 0 .2em var(--v-textColor-lighten5)
}
}
.hm-items {
min-width: 200px;
max-width: 400px;
flex-wrap: wrap;
row-gap: 3px;
gap:3px;
margin: 3px auto;
}
</style>
<!--
/**
* @copyright Copyright (c) 2021, Xgene Cloud Ltd
*
* @author Naveen MR <oof1lab@gmail.com>
* @author Pranav C Balan <pranavxc@gmail.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
-->

8
packages/nc-gui/components/project/spreadsheet/helpers/uiTypes.js

@ -43,10 +43,10 @@ const uiTypes = [
name: 'ForeignKey', name: 'ForeignKey',
icon: 'mdi-link-variant', icon: 'mdi-link-variant',
}, },
// { {
// name: 'LinkToAnotherRecord', name: 'LinkToAnotherRecord',
// icon: 'mdi-link-variant', icon: 'mdi-link-variant',
// }, },
{ {
name: 'SingleLineText', name: 'SingleLineText',
icon: 'mdi-format-color-text', icon: 'mdi-format-color-text',

1
packages/nc-gui/components/project/spreadsheet/rowsXcDataTable.vue

@ -174,6 +174,7 @@
@addNewRelationTab="addNewRelationTab" @addNewRelationTab="addNewRelationTab"
@expandRow="expandRow" @expandRow="expandRow"
@onRelationDelete="loadMeta" @onRelationDelete="loadMeta"
@loadTableData="loadTableData"
></xc-grid-view> ></xc-grid-view>
</template> </template>
<template v-else-if="selectedView && selectedView.show_as === 'gallery' "> <template v-else-if="selectedView && selectedView.show_as === 'gallery' ">

47
packages/nc-gui/components/project/spreadsheet/views/xcGridView.vue

@ -41,23 +41,26 @@
</th> </th>
<th v-for="bt in meta.belongsTo" <th v-for="(bt,i) in meta.belongsTo"
class="grey-border caption font-wight-regular" class="grey-border caption font-wight-regular"
:class="$store.state.windows.darkTheme ? 'grey darken-3 grey--text text--lighten-1' : 'grey lighten-4 grey--text text--darken-2'" :class="$store.state.windows.darkTheme ? 'grey darken-3 grey--text text--lighten-1' : 'grey lighten-4 grey--text text--darken-2'"
:key="i"
> >
{{ bt._rtn }} (Belongs To) {{ bt._rtn }} (Belongs To)
</th> </th>
<th v-for="hm in meta.hasMany" <th v-for="(hm,i) in meta.hasMany"
class="grey-border caption font-wight-regular" class="grey-border caption font-wight-regular"
:class="$store.state.windows.darkTheme ? 'grey darken-3 grey--text text--lighten-1' : 'grey lighten-4 grey--text text--darken-2'" :class="$store.state.windows.darkTheme ? 'grey darken-3 grey--text text--lighten-1' : 'grey lighten-4 grey--text text--darken-2'"
:key="i"
> >
{{ hm._tn }} (Has Many) {{ hm._tn }} (Has Many)
</th> </th>
<th v-for="mm in meta.manyToMany" <th v-for="(mm,i) in meta.manyToMany"
class="grey-border caption font-wight-regular" class="grey-border caption font-wight-regular"
:class="$store.state.windows.darkTheme ? 'grey darken-3 grey--text text--lighten-1' : 'grey lighten-4 grey--text text--darken-2'" :class="$store.state.windows.darkTheme ? 'grey darken-3 grey--text text--lighten-1' : 'grey lighten-4 grey--text text--darken-2'"
:key="i"
> >
{{ mm.rtn }} (Many To Many) {{ mm.rtn }} (Many To Many)
</th> </th>
@ -287,17 +290,32 @@
</td> </td>
<td v-for="(bt,i) in meta.belongsTo" class="caption"> <td v-for="(bt,i) in meta.belongsTo" class="caption" :key="i">
<v-chip x-small v-if="rowObj[bt._rtn]" :color="colors[i%colors.length]">{{ Object.values(rowObj[bt._rtn])[1] }}</v-chip> <v-chip x-small v-if="rowObj[bt._rtn]" :color="colors[i%colors.length]">{{
Object.values(rowObj[bt._rtn])[1]
}}
</v-chip>
</td> </td>
<td v-for="hm in meta.hasMany" class="caption"> <td v-for="(hm,i) in meta.hasMany" class="caption" :key="i">
<v-chip v-if="Array.isArray(rowObj[hm._tn])" x-small v-for="(v,i) in rowObj[hm._tn].map(v=>Object.values(v)[1])" :color="colors[i%colors.length]"> <template v-if="rowObj[hm._tn]">
{{ v }}
</v-chip>
<has-many-cell
:row="rowObj"
:value="rowObj[hm._tn]"
:meta="meta"
:hm="hm"
:nodes="nodes"
@loadTableData="$emit('loadTableData')"
/>
</template>
</td> </td>
<td v-for="mm in meta.manyToMany" class="caption"> <td v-for="(mm,i) in meta.manyToMany" class="caption" :key="i">
<v-chip v-if="rowObj[mm._rtn]" x-small v-for="(v,i) in rowObj[mm._rtn].map(v=>Object.values(v)[2])" :color="colors[i%colors.length]">{{ <v-chip v-if="rowObj[mm._rtn]" x-small v-for="(v,j) in rowObj[mm._rtn].map(v=>Object.values(v)[2])"
:color="colors[i%colors.length]" :key="`${i}-${j}`">{{
v v
}} }}
</v-chip> </v-chip>
@ -331,9 +349,10 @@ import EditColumn from "@/components/project/spreadsheet/editColumn/editColumn";
import TableCell from "@/components/project/spreadsheet/editableCell/tableCell"; import TableCell from "@/components/project/spreadsheet/editableCell/tableCell";
import colors from "@/mixins/colors"; import colors from "@/mixins/colors";
import columnStyling from "@/components/project/spreadsheet/helpers/columnStyling"; import columnStyling from "@/components/project/spreadsheet/helpers/columnStyling";
import HasManyCell from "@/components/project/spreadsheet/editableCell/hasManyCell";
export default { export default {
components: {TableCell, EditColumn, EditableCell, HeaderCell}, components: {HasManyCell, TableCell, EditColumn, EditableCell, HeaderCell},
mixins: [colors], mixins: [colors],
props: { props: {
relationType: String, relationType: String,
@ -842,8 +861,8 @@ th:first-child, td:first-child {
transform: rotate(90deg); transform: rotate(90deg);
} }
th{ th {
min-width:100px; min-width: 100px;
} }

17
packages/nocodb/src/lib/noco/common/BaseApiBuilder.ts

@ -1499,15 +1499,20 @@ export default abstract class BaseApiBuilder<T extends Noco> implements XcDynami
protected async getManyToManyRelations() { protected async getManyToManyRelations() {
const metas = new Set<any>(); const metas = new Set<any>();
const assocMetas = new Set<any>();
for (const meta of Object.values(this.metas)) { for (const meta of Object.values(this.metas)) {
// check if table is a Bridge table(or Associative Table) by checking // check if table is a Bridge table(or Associative Table) by checking
// number of foreign keys and columns // number of foreign keys and columns
if (meta.belongsTo?.length === 2 && meta.columns.length < 4) { if (meta.belongsTo?.length === 2 && meta.columns.length < 5) {
const tableMetaA = this.metas[meta.belongsTo[0].rtn]; const tableMetaA = this.metas[meta.belongsTo[0].rtn];
const tableMetaB = this.metas[meta.belongsTo[1].rtn]; const tableMetaB = this.metas[meta.belongsTo[1].rtn];
/* // remove hasmany relation with associate table from tables
tableMetaA.hasMany.splice(tableMetaA.hasMany.findIndex(hm => hm.tn === meta.tn), 1)
tableMetaB.hasMany.splice(tableMetaB.hasMany.findIndex(hm => hm.tn === meta.tn), 1)*/
// add manytomany data under metadata of both related columns // add manytomany data under metadata of both related columns
tableMetaA.manyToMany = tableMetaA.manyToMany || []; tableMetaA.manyToMany = tableMetaA.manyToMany || [];
tableMetaA.manyToMany.push({ tableMetaA.manyToMany.push({
@ -1539,6 +1544,7 @@ export default abstract class BaseApiBuilder<T extends Noco> implements XcDynami
}) })
metas.add(tableMetaA) metas.add(tableMetaA)
metas.add(tableMetaB) metas.add(tableMetaB)
assocMetas.add(meta)
} }
} }
@ -1551,6 +1557,15 @@ export default abstract class BaseApiBuilder<T extends Noco> implements XcDynami
XcCache.del([this.projectId, this.dbAlias, 'table', meta.tn].join('::')); XcCache.del([this.projectId, this.dbAlias, 'table', meta.tn].join('::'));
this.models[meta.tn] = this.getBaseModel(meta) this.models[meta.tn] = this.getBaseModel(meta)
} }
// Update metadata of associative table
for (const meta of assocMetas) {
await this.xcMeta.metaUpdate(this.projectId, this.dbAlias, 'nc_models', {
mm: 1,
}, {title: meta.tn})
XcCache.del([this.projectId, this.dbAlias, 'table', meta.tn].join('::'));
this.models[meta.tn] = this.getBaseModel(meta)
}
} }
} }

5
packages/nocodb/src/lib/noco/common/XcMigrationSource.ts

@ -1,4 +1,5 @@
import * as project from '../migrations/nc_001_init'; import * as project from '../migrations/nc_001_init';
import * as m2m from '../migrations/nc_002_add_m2m';
// Create a custom migration source class // Create a custom migration source class
export default class XcMigrationSource{ export default class XcMigrationSource{
@ -7,7 +8,7 @@ export default class XcMigrationSource{
// arguments to getMigrationName and getMigration // arguments to getMigrationName and getMigration
public getMigrations(): Promise<any> { public getMigrations(): Promise<any> {
// In this example we are just returning migration names // In this example we are just returning migration names
return Promise.resolve(['project']) return Promise.resolve(['project','m2m'])
} }
public getMigrationName(migration): string { public getMigrationName(migration): string {
@ -18,6 +19,8 @@ export default class XcMigrationSource{
switch (migration) { switch (migration) {
case 'project': case 'project':
return project; return project;
case 'm2m':
return m2m;
} }
} }
} }

85
packages/nocodb/src/lib/noco/gql/GqlApiBuilder.ts

@ -643,55 +643,16 @@ export class GqlApiBuilder extends BaseApiBuilder<Noco> implements XcMetaMgr {
/* has many relation list loader with middleware */ /* has many relation list loader with middleware */
const mw = new GqlMiddleware(this.acls, hm.tn, '', this.models); const mw = new GqlMiddleware(this.acls, hm.tn, '', this.models);
const listLoader = new DataLoader( /* has many relation list loader with middleware */
BaseType.applyMiddlewareForLoader( this.addHmListResolverMethodToType(tn, hm, mw, {}, listPropName, colNameAlias);
[mw.middleware],
async ids => {
const data = await this.models[tn].hasManyListGQL({
ids,
child: hm.tn
})
return ids.map(id => data[id] ? data[id].map(c => new self.types[hm.tn](c)) : []);
},
[mw.postLoaderMiddleware]
));
/* defining HasMany list method within GQL Type class */
Object.defineProperty(this.types[tn].prototype, `${listPropName}`, {
async value(args, context, info): Promise<any> {
return listLoader.load([this[colNameAlias], args, context, info]);
},
configurable: true
})
if (countPropName in this.types[tn].prototype) { if (countPropName in this.types[tn].prototype) {
continue; continue;
} }
// create count loader with middleware
{ {
const mw = new GqlMiddleware(this.acls, hm.tn, '', this.models); const mw = new GqlMiddleware(this.acls, hm.tn, null, this.models);
const countLoader = new DataLoader(
BaseType.applyMiddlewareForLoader( // create count loader with middleware
[mw.middleware], this.addHmCountResolverMethodToType(hm, mw, tn, {}, countPropName, colNameAlias);
async ids => {
const data = await this.models[tn].hasManyListCount({
ids,
child: hm.tn
})
return data;
},
[mw.postLoaderMiddleware]
));
// defining HasMany count method within GQL Type class
Object.defineProperty(this.types[tn].prototype, `${countPropName}`, {
async value(args, context, info): Promise<any> {
return countLoader.load([this[colNameAlias], args, context, info]);
},
configurable: true
})
} }
this.log(`xcTablesPopulate : Inserting loader metadata of '%s' and '%s' loaders`, listPropName, countPropName); this.log(`xcTablesPopulate : Inserting loader metadata of '%s' and '%s' loaders`, listPropName, countPropName);
@ -716,33 +677,21 @@ export class GqlApiBuilder extends BaseApiBuilder<Noco> implements XcMetaMgr {
for (const bt of schema.belongsTo) { for (const bt of schema.belongsTo) {
const colNameAlias = self.models[bt.tn]?.columnToAlias[bt.cn]; const colNameAlias = self.models[bt.tn]?.columnToAlias[bt.cn];
const propName = `${inflection.camelize(bt._rtn, false)}Read`; const propName = `${inflection.camelize(bt._rtn, false)}Read`;
if (propName in this.types[tn].prototype) { if (propName in this.types[tn].prototype) {
continue; continue;
} }
this.log(`xcTablesPopulate : Populating '%s' loader`, propName);
// create read loader with middleware // create read loader with middleware
const mw = new GqlMiddleware(this.acls, bt.rtn, '', this.models); {
const readLoader = new DataLoader( const mw = new GqlMiddleware(this.acls, bt.rtn, null, this.models);
BaseType.applyMiddlewareForLoader( this.log(`xcTablesRead : Creating loader for '%s'`, `${tn}Bt${bt.rtn}`);
[mw.middleware], this.adBtResolverMethodToType(propName, mw,
async ids => { tn, bt, colNameAlias, colNameAlias, null);
const data = await self.models[bt.rtn].list({ }
where: `(${bt.rcn},in,${ids.join(',')})`,
limit: ids.length
})
const gs = _.groupBy(data, bt.rcn);
return ids.map(async id => gs?.[id]?.[0] && new self.types[bt.rtn](gs[id][0]))
},
[mw.postLoaderMiddleware]
));
// defining BelongsTo read method within GQL Type class
Object.defineProperty(this.types[tn].prototype, `${propName}`, {
async value(args, context, info): Promise<any> {
return readLoader.load([this[colNameAlias], args, context, info]);
},
configurable: true
});
this.log(`xcTablesPopulate : Inserting loader metadata of '%s' loader`, propName); this.log(`xcTablesPopulate : Inserting loader metadata of '%s' loader`, propName);
await this.xcMeta.metaInsert(this.projectId, this.dbAlias, 'nc_loaders', { await this.xcMeta.metaInsert(this.projectId, this.dbAlias, 'nc_loaders', {

43
packages/nocodb/src/lib/noco/migrations/nc_002_add_m2m.ts

@ -0,0 +1,43 @@
import Knex from "knex";
const up = async (knex: Knex) => {
await knex.schema.alterTable('nc_models', table => {
table.integer('mm');
table.text('m_to_m_meta');
})
};
const down = async (knex) => {
await knex.schema.alterTable('nc_models', table => {
table.dropColumns('mm', 'm_to_m_meta');
})
};
export {
up, down
}
/**
* @copyright Copyright (c) 2021, Xgene Cloud Ltd
*
* @author Naveen MR <oof1lab@gmail.com>
* @author Pranav C Balan <pranavxc@gmail.com>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
Loading…
Cancel
Save