Browse Source

feat: group by - virtual columns - WIP

Signed-off-by: Pranav C <pranavxc@gmail.com>
pull/6489/head
Pranav C 1 year ago
parent
commit
dc87247088
  1. 228
      packages/nc-gui/components/smartsheet/ApiSnippet.vue
  2. 4
      packages/nc-gui/components/smartsheet/toolbar/GroupByMenu.vue
  3. 164
      packages/nocodb/src/db/BaseModelSqlv2.ts

228
packages/nc-gui/components/smartsheet/ApiSnippet.vue

@ -1,228 +0,0 @@
<script setup lang="ts">
import HTTPSnippet from 'httpsnippet'
import {
ActiveViewInj,
MetaInj,
inject,
message,
ref,
storeToRefs,
useCopy,
useGlobal,
useI18n,
useProject,
useSmartsheetStoreOrThrow,
useVModel,
useViewData,
watch,
} from '#imports'
const props = defineProps<{
modelValue: boolean
}>()
const emits = defineEmits(['update:modelValue'])
const { t } = useI18n()
const projectStore = useProject()
const { project } = storeToRefs(projectStore)
const { appInfo, token } = useGlobal()
const meta = inject(MetaInj, ref())
const view = inject(ActiveViewInj, ref())
const { xWhere } = useSmartsheetStoreOrThrow()
const { queryParams } = useViewData(meta, view, xWhere)
const { copy } = useCopy()
const vModel = useVModel(props, 'modelValue', emits)
const langs = [
{
name: 'shell',
clients: ['curl', 'wget'],
},
{
name: 'javascript',
clients: ['axios', 'fetch', 'jquery', 'xhr'],
},
{
name: 'node',
clients: ['axios', 'fetch', 'request', 'native', 'unirest'],
},
{
name: 'nocodb-sdk',
clients: ['javascript', 'node'],
},
{
name: 'php',
},
{
name: 'python',
clients: ['python3', 'requests'],
},
{
name: 'ruby',
},
{
name: 'java',
},
{
name: 'c',
},
]
const selectedClient = ref<string | undefined>(langs[0].clients && langs[0].clients[0])
const selectedLangName = ref(langs[0].name)
const apiUrl = computed(
() =>
new URL(
`/api/v1/db/data/noco/${project.value.id}/${meta.value?.title}/views/${view.value?.title}`,
(appInfo.value && appInfo.value.ncSiteUrl) || '/',
).href,
)
const snippet = computed(
() =>
new HTTPSnippet({
method: 'GET',
headers: [{ name: 'xc-auth', value: token.value, comment: 'JWT Auth token' }],
url: apiUrl.value,
queryString: Object.entries(queryParams.value || {}).map(([name, value]) => {
return {
name,
value: String(value),
}
}),
}),
)
const activeLang = computed(() => langs.find((lang) => lang.name === selectedLangName.value))
const code = computed(() => {
if (activeLang.value?.name === 'nocodb-sdk') {
return `${selectedClient.value === 'node' ? 'const { Api } = require("nocodb-sdk");' : 'import { Api } from "nocodb-sdk";'}
const api = new Api({
baseURL: "${(appInfo.value && appInfo.value.ncSiteUrl) || '/'}",
headers: {
"xc-auth": ${JSON.stringify(token.value as string)}
}
})
api.dbViewRow.list(
"noco",
${JSON.stringify(project.value.title)},
${JSON.stringify(meta.value?.title)},
${JSON.stringify(view.value?.title)}, ${JSON.stringify(queryParams.value, null, 4)}).then(function (data) {
console.log(data);
}).catch(function (error) {
console.error(error);
});
`
}
return snippet.value.convert(
activeLang.value?.name,
selectedClient.value || (activeLang.value?.clients && activeLang.value?.clients[0]),
{},
)
})
const onCopyToClipboard = async () => {
try {
await copy(code.value)
// Copied to clipboard
message.info(t('msg.info.copiedToClipboard'))
} catch (e: any) {
message.error(e.message)
}
}
const afterVisibleChange = (visible: boolean) => {
vModel.value = visible
}
watch(activeLang, (newLang) => {
selectedClient.value = newLang?.clients?.[0]
})
</script>
<template>
<a-drawer
v-model:visible="vModel"
class="h-full relative nc-drawer-api-snippet"
placement="right"
size="large"
:closable="false"
@after-visible-change="afterVisibleChange"
>
<div class="flex flex-col w-full h-full p-4">
<!-- Code Snippet -->
<a-typography-title :level="4" class="pb-1">{{ $t('title.codeSnippet') }}</a-typography-title>
<a-tabs v-model:activeKey="selectedLangName" class="!h-full">
<a-tab-pane v-for="item in langs" :key="item.name" class="!h-full">
<template #tab>
<div class="uppercase !text-xs select-none">
{{ item.name }}
</div>
</template>
<LazyMonacoEditor
class="h-[60vh] border-1 border-gray-100 py-4 rounded-sm"
:model-value="code"
:read-only="true"
lang="typescript"
:validate="false"
:disable-deep-compare="true"
hide-minimap
/>
<div v-if="activeLang?.clients" class="flex flex-row w-full justify-end space-x-3 mt-4 uppercase">
<a-select v-model:value="selectedClient" style="width: 6rem" dropdown-class-name="nc-dropdown-snippet-active-lang">
<a-select-option v-for="(client, i) in activeLang?.clients" :key="i" class="!w-full uppercase" :value="client">
{{ client }}
</a-select-option>
</a-select>
<a-button
v-e="[
'c:snippet:copy',
{ client: activeLang?.clients && (selectedClient || activeLang?.clients[0]), lang: activeLang?.name },
]"
type="primary"
@click="onCopyToClipboard"
>
{{ $t('general.copy') }}
</a-button>
</div>
<div class="absolute bottom-4 flex flex-row justify-center w-[95%]">
<a
v-e="['e:hiring']"
class="px-4 py-2 ! rounded shadow"
href="https://angel.co/company/nocodb"
target="_blank"
@click.stop
>
🚀 {{ $t('labels.weAreHiring') }}! 🚀
</a>
</div>
</a-tab-pane>
</a-tabs>
</div>
</a-drawer>
</template>
<style scoped>
:deep(.ant-tabs-tab + .ant-tabs-tab) {
@apply !ml-7;
}
</style>

4
packages/nc-gui/components/smartsheet/toolbar/GroupByMenu.vue

@ -21,6 +21,10 @@ const groupingUidt = [
UITypes.Date,
UITypes.SingleLineText,
UITypes.Number,
UITypes.Rollup,
UITypes.Lookup,
UITypes.Links,
UITypes.Formula,
]
const meta = inject(MetaInj, ref())

164
packages/nocodb/src/db/BaseModelSqlv2.ts

@ -497,21 +497,95 @@ class BaseModelSqlv2 {
args.column_name = args.column_name || '';
const groupByColumns = await this.model.getColumns().then((cols) =>
args.column_name.split(',').map((col) => {
const cols = await this.model.getColumns();
const selectors = [];
const groupBySelector = [];
const groupByColumns = await Promise.all(
args.column_name.split(',').map(async (col) => {
const column = cols.find(
(c) => c.column_name === col || c.title === col,
);
if (!column) {
throw NcError.notFound('Column not found');
}
switch (column.uidt) {
case UITypes.Rollup:
selectors.push(
(
await genRollupSelectv2({
baseModelSqlv2: this,
// tn: this.title,
knex: this.dbDriver,
// column,
// alias,
columnOptions: (await column.getColOptions()) as RollupColumn,
})
).builder.as(sanitize(column.title)),
);
groupBySelector.push(
// (
// await genRollupSelectv2({
// baseModelSqlv2: this,
// // tn: this.title,
// knex: this.dbDriver,
// // column,
// // alias,
// columnOptions: (await column.getColOptions()) as RollupColumn,
// })
// ).builder,
sanitize(column.title),
);
break;
case UITypes.Formula:
let selectQb;
try {
const _selectQb = await this.getSelectQueryBuilderForFormula(
column,
);
selectQb = this.dbDriver.raw(`?? as ??`, [
_selectQb.builder,
sanitize(column.title),
]);
} catch (e) {
console.log(e);
// return dummy select
selectQb = this.dbDriver.raw(`'ERR' as ??`, [
sanitize(column.title),
]);
}
selectors.push(selectQb);
groupBySelector.push(
// (
// await genRollupSelectv2({
// baseModelSqlv2: this,
// // tn: this.title,
// knex: this.dbDriver,
// // column,
// // alias,
// columnOptions: (await column.getColOptions()) as RollupColumn,
// })
// ).builder,
column.title,
);
break;
}
return column.column_name;
}),
);
const qb = this.dbDriver(this.tnPath);
qb.count(`${this.model.primaryKey?.column_name || '*'} as count`);
qb.select(...groupByColumns);
// groupby-replace
// qb.select(...groupByColumns);
qb.select(...selectors);
if (+rest?.shuffle) {
await this.shuffle({ qb });
@ -548,6 +622,7 @@ class BaseModelSqlv2 {
qb,
);
// qb.groupBy(...groupByColumns);
qb.groupBy(...groupByColumns);
if (!sorts)
@ -574,21 +649,80 @@ class BaseModelSqlv2 {
args.column_name = args.column_name || '';
const groupByColumns = await this.model.getColumns().then((cols) =>
args.column_name.split(',').map((col) => {
const column = cols.find(
(c) => c.column_name === col || c.title === col,
);
if (!column) {
throw NcError.notFound('Column not found');
}
return column.column_name;
}),
const selectors = [];
const groupBySelector = [];
await this.model.getColumns().then((cols) =>
Promise.all(
args.column_name.split(',').map(async (col) => {
const column = cols.find(
(c) => c.column_name === col || c.title === col,
);
if (!column) {
throw NcError.notFound('Column not found');
}
switch (column.uidt) {
case UITypes.Rollup:
selectors.push(
(
await genRollupSelectv2({
baseModelSqlv2: this,
// tn: this.title,
knex: this.dbDriver,
// column,
// alias,
columnOptions:
(await column.getColOptions()) as RollupColumn,
})
).builder.as(sanitize(column.title)),
);
groupBySelector.push(sanitize(column.title));
break;
case UITypes.Formula:
let selectQb;
try {
const _selectQb = await this.getSelectQueryBuilderForFormula(
column,
);
selectQb = this.dbDriver.raw(`?? as ??`, [
_selectQb.builder,
sanitize(column.title),
]);
} catch (e) {
console.log(e);
// return dummy select
selectQb = this.dbDriver.raw(`'ERR' as ??`, [
sanitize(column.title),
]);
}
selectors.push(selectQb);
groupBySelector.push(
// (
// await genRollupSelectv2({
// baseModelSqlv2: this,
// // tn: this.title,
// knex: this.dbDriver,
// // column,
// // alias,
// columnOptions: (await column.getColOptions()) as RollupColumn,
// })
// ).builder,
column.title,
);
break;
}
return column.column_name;
}),
),
);
const qb = this.dbDriver(this.tnPath);
qb.count(`${this.model.primaryKey?.column_name || '*'} as count`);
qb.select(...groupByColumns);
qb.select(...selectors);
const aliasColObjMap = await this.model.getAliasColObjMap();
@ -619,7 +753,7 @@ class BaseModelSqlv2 {
qb,
);
qb.groupBy(...groupByColumns);
qb.groupBy(...groupBySelector);
const qbP = this.dbDriver
.count('*', { as: 'count' })

Loading…
Cancel
Save