Merge branch 'v3-ui' into BUDI-8775/new-filtering-doesnt-work-with-queries

This commit is contained in:
Adria Navarro 2024-10-29 15:09:30 +01:00 committed by GitHub
commit a8a488d10a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
12 changed files with 162 additions and 43 deletions

View File

@ -1,6 +1,6 @@
{ {
"$schema": "node_modules/lerna/schemas/lerna-schema.json", "$schema": "node_modules/lerna/schemas/lerna-schema.json",
"version": "2.33.4", "version": "2.33.5",
"npmClient": "yarn", "npmClient": "yarn",
"packages": [ "packages": [
"packages/*", "packages/*",

View File

@ -237,7 +237,10 @@ export function validInherits(
export function builtinRoleToNumber(id: string) { export function builtinRoleToNumber(id: string) {
const builtins = getBuiltinRoles() const builtins = getBuiltinRoles()
const MAX = Object.values(builtins).length + 1 const MAX = Object.values(builtins).length + 1
if (id === BUILTIN_IDS.ADMIN || id === BUILTIN_IDS.BUILDER) { if (
roleIDsAreEqual(id, BUILTIN_IDS.ADMIN) ||
roleIDsAreEqual(id, BUILTIN_IDS.BUILDER)
) {
return MAX return MAX
} }
let role = builtins[id], let role = builtins[id],
@ -274,7 +277,9 @@ export async function roleToNumber(id: string) {
// find the built-in roles, get their number, sort it, then get the last one // find the built-in roles, get their number, sort it, then get the last one
const highestBuiltin: number | undefined = role.inherits const highestBuiltin: number | undefined = role.inherits
.map(roleId => { .map(roleId => {
const foundRole = hierarchy.find(role => role._id === roleId) const foundRole = hierarchy.find(role =>
roleIDsAreEqual(role._id!, roleId)
)
if (foundRole) { if (foundRole) {
return findNumber(foundRole) + 1 return findNumber(foundRole) + 1
} }
@ -398,7 +403,7 @@ async function getAllUserRoles(
): Promise<RoleDoc[]> { ): Promise<RoleDoc[]> {
const allRoles = await getAllRoles() const allRoles = await getAllRoles()
// admins have access to all roles // admins have access to all roles
if (userRoleId === BUILTIN_IDS.ADMIN) { if (roleIDsAreEqual(userRoleId, BUILTIN_IDS.ADMIN)) {
return allRoles return allRoles
} }
@ -509,17 +514,21 @@ export async function getAllRoles(appId?: string): Promise<RoleDoc[]> {
// need to combine builtin with any DB record of them (for sake of permissions) // need to combine builtin with any DB record of them (for sake of permissions)
for (let builtinRoleId of externalBuiltinRoles) { for (let builtinRoleId of externalBuiltinRoles) {
const builtinRole = builtinRoles[builtinRoleId] const builtinRole = builtinRoles[builtinRoleId]
const dbBuiltin = roles.filter( const dbBuiltin = roles.filter(dbRole =>
dbRole => roleIDsAreEqual(dbRole._id!, builtinRoleId)
getExternalRoleID(dbRole._id!, dbRole.version) === builtinRoleId
)[0] )[0]
if (dbBuiltin == null) { if (dbBuiltin == null) {
roles.push(builtinRole || builtinRoles.BASIC) roles.push(builtinRole || builtinRoles.BASIC)
} else { } else {
// remove role and all back after combining with the builtin // remove role and all back after combining with the builtin
roles = roles.filter(role => role._id !== dbBuiltin._id) roles = roles.filter(role => role._id !== dbBuiltin._id)
dbBuiltin._id = getExternalRoleID(dbBuiltin._id!, dbBuiltin.version) dbBuiltin._id = getExternalRoleID(builtinRole._id!, dbBuiltin.version)
roles.push(Object.assign(builtinRole, dbBuiltin)) roles.push({
...builtinRole,
...dbBuiltin,
name: builtinRole.name,
_id: getExternalRoleID(builtinRole._id!, builtinRole.version),
})
} }
} }
// check permissions // check permissions
@ -565,9 +574,9 @@ export class AccessController {
if ( if (
tryingRoleId == null || tryingRoleId == null ||
tryingRoleId === "" || tryingRoleId === "" ||
tryingRoleId === userRoleId || roleIDsAreEqual(tryingRoleId, BUILTIN_IDS.BUILDER) ||
tryingRoleId === BUILTIN_IDS.BUILDER || roleIDsAreEqual(userRoleId!, tryingRoleId) ||
userRoleId === BUILTIN_IDS.BUILDER roleIDsAreEqual(userRoleId!, BUILTIN_IDS.BUILDER)
) { ) {
return true return true
} }

View File

@ -22,7 +22,7 @@
const context = getContext("context") const context = getContext("context")
const component = getContext("component") const component = getContext("component")
const { API, fetchDatasourceSchema } = getContext("sdk") const { fetchDatasourceSchema, fetchDatasourceDefinition } = getContext("sdk")
const getInitialFormStep = () => { const getInitialFormStep = () => {
const parsedFormStep = parseInt(initialFormStep) const parsedFormStep = parseInt(initialFormStep)
@ -32,9 +32,9 @@
return parsedFormStep return parsedFormStep
} }
let loaded = false let definition
let schema let schema
let table let loaded = false
let currentStep = getContext("current-step") || writable(getInitialFormStep()) let currentStep = getContext("current-step") || writable(getInitialFormStep())
$: fetchSchema(dataSource) $: fetchSchema(dataSource)
@ -84,12 +84,10 @@
// Fetches the form schema from this form's dataSource // Fetches the form schema from this form's dataSource
const fetchSchema = async dataSource => { const fetchSchema = async dataSource => {
if (dataSource?.tableId && !dataSource?.type?.startsWith("query")) {
try { try {
table = await API.fetchTableDefinition(dataSource.tableId) definition = await fetchDatasourceDefinition(dataSource)
} catch (error) { } catch (error) {
table = null definition = null
}
} }
const res = await fetchDatasourceSchema(dataSource) const res = await fetchDatasourceSchema(dataSource)
schema = res || {} schema = res || {}
@ -121,7 +119,7 @@
{readonly} {readonly}
{actionType} {actionType}
{schema} {schema}
{table} {definition}
{initialValues} {initialValues}
{disableSchemaValidation} {disableSchemaValidation}
{editAutoColumns} {editAutoColumns}

View File

@ -10,7 +10,7 @@
export let initialValues export let initialValues
export let size export let size
export let schema export let schema
export let table export let definition
export let disableSchemaValidation = false export let disableSchemaValidation = false
export let editAutoColumns = false export let editAutoColumns = false
@ -164,7 +164,7 @@
schemaConstraints, schemaConstraints,
validationRules, validationRules,
field, field,
table definition
) )
// Sanitise the default value to ensure it doesn't contain invalid data // Sanitise the default value to ensure it doesn't contain invalid data
@ -338,7 +338,7 @@
schemaConstraints, schemaConstraints,
validationRules, validationRules,
field, field,
table definition
) )
// Update validator // Update validator

View File

@ -5,17 +5,17 @@ import { Helpers } from "@budibase/bbui"
/** /**
* Creates a validation function from a combination of schema-level constraints * Creates a validation function from a combination of schema-level constraints
* and custom validation rules * and custom validation rules
* @param schemaConstraints any schema level constraints from the table * @param schemaConstraints any schema level constraints from the datasource
* @param customRules any custom validation rules * @param customRules any custom validation rules
* @param field the field name we are evaluating * @param field the field name we are evaluating
* @param table the definition of the table we are evaluating * @param definition the definition of the datasource we are evaluating
* @returns {function} a validator function which accepts test values * @returns {function} a validator function which accepts test values
*/ */
export const createValidatorFromConstraints = ( export const createValidatorFromConstraints = (
schemaConstraints, schemaConstraints,
customRules, customRules,
field, field,
table definition
) => { ) => {
let rules = [] let rules = []
@ -23,7 +23,7 @@ export const createValidatorFromConstraints = (
if (schemaConstraints) { if (schemaConstraints) {
// Required constraint // Required constraint
if ( if (
field === table?.primaryDisplay || field === definition?.primaryDisplay ||
schemaConstraints.presence?.allowEmpty === false || schemaConstraints.presence?.allowEmpty === false ||
schemaConstraints.presence === true schemaConstraints.presence === true
) { ) {

View File

@ -26,7 +26,10 @@ import Provider from "components/context/Provider.svelte"
import Block from "components/Block.svelte" import Block from "components/Block.svelte"
import BlockComponent from "components/BlockComponent.svelte" import BlockComponent from "components/BlockComponent.svelte"
import { ActionTypes } from "./constants" import { ActionTypes } from "./constants"
import { fetchDatasourceSchema } from "./utils/schema.js" import {
fetchDatasourceSchema,
fetchDatasourceDefinition,
} from "./utils/schema.js"
import { getAPIKey } from "./utils/api.js" import { getAPIKey } from "./utils/api.js"
import { enrichButtonActions } from "./utils/buttonActions.js" import { enrichButtonActions } from "./utils/buttonActions.js"
import { processStringSync, makePropSafe } from "@budibase/string-templates" import { processStringSync, makePropSafe } from "@budibase/string-templates"
@ -66,6 +69,7 @@ export default {
linkable, linkable,
getAction, getAction,
fetchDatasourceSchema, fetchDatasourceSchema,
fetchDatasourceDefinition,
fetchData, fetchData,
QueryUtils, QueryUtils,
ContextScopes: Constants.ContextScopes, ContextScopes: Constants.ContextScopes,

View File

@ -10,16 +10,13 @@ import ViewV2Fetch from "@budibase/frontend-core/src/fetch/ViewV2Fetch.js"
import QueryArrayFetch from "@budibase/frontend-core/src/fetch/QueryArrayFetch" import QueryArrayFetch from "@budibase/frontend-core/src/fetch/QueryArrayFetch"
/** /**
* Fetches the schema of any kind of datasource. * Constructs a fetch instance for a given datasource.
* All datasource fetch classes implement their own functionality to get the * All datasource fetch classes implement their own functionality to get the
* schema of a datasource of their respective types. * schema of a datasource of their respective types.
* @param datasource the datasource to fetch the schema for * @param datasource the datasource
* @param options options for enriching the schema * @returns
*/ */
export const fetchDatasourceSchema = async ( const getDatasourceFetchInstance = datasource => {
datasource,
options = { enrichRelationships: false, formSchema: false }
) => {
const handler = { const handler = {
table: TableFetch, table: TableFetch,
view: ViewFetch, view: ViewFetch,
@ -34,10 +31,23 @@ export const fetchDatasourceSchema = async (
if (!handler) { if (!handler) {
return null return null
} }
const instance = new handler({ API }) return new handler({ API })
}
// Get the datasource definition and then schema /**
const definition = await instance.getDefinition(datasource) * Fetches the schema of any kind of datasource.
* @param datasource the datasource to fetch the schema for
* @param options options for enriching the schema
*/
export const fetchDatasourceSchema = async (
datasource,
options = { enrichRelationships: false, formSchema: false }
) => {
const instance = getDatasourceFetchInstance(datasource)
const definition = await instance?.getDefinition(datasource)
if (!definition) {
return null
}
// Get the normal schema as long as we aren't wanting a form schema // Get the normal schema as long as we aren't wanting a form schema
let schema let schema
@ -75,6 +85,15 @@ export const fetchDatasourceSchema = async (
return instance.enrichSchema(schema) return instance.enrichSchema(schema)
} }
/**
* Fetches the definition of any kind of datasource.
* @param datasource the datasource to fetch the schema for
*/
export const fetchDatasourceDefinition = async datasource => {
const instance = getDatasourceFetchInstance(datasource)
return await instance?.getDefinition(datasource)
}
/** /**
* Fetches the schema of relationship fields for a SQL table schema * Fetches the schema of relationship fields for a SQL table schema
* @param schema the schema to enrich * @param schema the schema to enrich

View File

@ -6,6 +6,7 @@ export const buildViewV2Endpoints = API => ({
fetchDefinition: async viewId => { fetchDefinition: async viewId => {
return await API.get({ return await API.get({
url: `/api/v2/views/${encodeURIComponent(viewId)}`, url: `/api/v2/views/${encodeURIComponent(viewId)}`,
cache: true,
}) })
}, },
/** /**

View File

@ -763,12 +763,25 @@ describe.each([
expect(row.food).toEqual(["apple", "orange"]) expect(row.food).toEqual(["apple", "orange"])
}) })
it("creates a new row with a default value when given an empty list", async () => {
const row = await config.api.row.save(table._id!, { food: [] })
expect(row.food).toEqual(["apple", "orange"])
})
it("does not use default value if value specified", async () => { it("does not use default value if value specified", async () => {
const row = await config.api.row.save(table._id!, { const row = await config.api.row.save(table._id!, {
food: ["orange"], food: ["orange"],
}) })
expect(row.food).toEqual(["orange"]) expect(row.food).toEqual(["orange"])
}) })
it("resets back to its default value when empty", async () => {
let row = await config.api.row.save(table._id!, {
food: ["orange"],
})
row = await config.api.row.save(table._id!, { ...row, food: [] })
expect(row.food).toEqual(["apple", "orange"])
})
}) })
describe("user column", () => { describe("user column", () => {
@ -835,6 +848,62 @@ describe.each([
}) })
}) })
describe("boolean column", () => {
beforeAll(async () => {
table = await config.api.table.save(
saveTableRequest({
schema: {
active: {
name: "active",
type: FieldType.BOOLEAN,
default: "true",
},
},
})
)
})
it("creates a new row with a default value successfully", async () => {
const row = await config.api.row.save(table._id!, {})
expect(row.active).toEqual(true)
})
it("does not use default value if value specified", async () => {
const row = await config.api.row.save(table._id!, {
active: false,
})
expect(row.active).toEqual(false)
})
})
describe("bigint column", () => {
beforeAll(async () => {
table = await config.api.table.save(
saveTableRequest({
schema: {
bigNumber: {
name: "bigNumber",
type: FieldType.BIGINT,
default: "1234567890",
},
},
})
)
})
it("creates a new row with a default value successfully", async () => {
const row = await config.api.row.save(table._id!, {})
expect(row.bigNumber).toEqual("1234567890")
})
it("does not use default value if value specified", async () => {
const row = await config.api.row.save(table._id!, {
bigNumber: "9876543210",
})
expect(row.bigNumber).toEqual("9876543210")
})
})
describe("bindings", () => { describe("bindings", () => {
describe("string column", () => { describe("string column", () => {
beforeAll(async () => { beforeAll(async () => {

View File

@ -134,7 +134,12 @@ async function processDefaultValues(table: Table, row: Row) {
} }
for (const [key, schema] of Object.entries(table.schema)) { for (const [key, schema] of Object.entries(table.schema)) {
if ("default" in schema && schema.default != null && row[key] == null) { const isEmpty =
row[key] == null ||
row[key] === "" ||
(Array.isArray(row[key]) && row[key].length === 0)
if ("default" in schema && schema.default != null && isEmpty) {
let processed: string | string[] let processed: string | string[]
if (Array.isArray(schema.default)) { if (Array.isArray(schema.default)) {
processed = schema.default.map(val => processStringSync(val, ctx)) processed = schema.default.map(val => processStringSync(val, ctx))

View File

@ -57,12 +57,12 @@ const allowDefaultColumnByType: Record<FieldType, boolean> = {
[FieldType.STRING]: true, [FieldType.STRING]: true,
[FieldType.OPTIONS]: true, [FieldType.OPTIONS]: true,
[FieldType.ARRAY]: true, [FieldType.ARRAY]: true,
[FieldType.BIGINT]: true,
[FieldType.BOOLEAN]: true,
[FieldType.AUTO]: false, [FieldType.AUTO]: false,
[FieldType.INTERNAL]: false, [FieldType.INTERNAL]: false,
[FieldType.BARCODEQR]: false, [FieldType.BARCODEQR]: false,
[FieldType.BIGINT]: false,
[FieldType.BOOLEAN]: false,
[FieldType.FORMULA]: false, [FieldType.FORMULA]: false,
[FieldType.AI]: false, [FieldType.AI]: false,
[FieldType.ATTACHMENTS]: false, [FieldType.ATTACHMENTS]: false,

View File

@ -186,6 +186,16 @@ export interface ArrayFieldMetadata extends BaseFieldSchema {
default?: string[] default?: string[]
} }
export interface BooleanFieldMetadata extends BaseFieldSchema {
type: FieldType.BOOLEAN
default?: string
}
export interface BigIntFieldMetadata extends BaseFieldSchema {
type: FieldType.BIGINT
default?: string
}
interface BaseFieldSchema extends UIFieldMetadata { interface BaseFieldSchema extends UIFieldMetadata {
type: FieldType type: FieldType
name: string name: string
@ -214,6 +224,8 @@ interface OtherFieldMetadata extends BaseFieldSchema {
| FieldType.STRING | FieldType.STRING
| FieldType.ARRAY | FieldType.ARRAY
| FieldType.OPTIONS | FieldType.OPTIONS
| FieldType.BOOLEAN
| FieldType.BIGINT
> >
} }
@ -233,6 +245,8 @@ export type FieldSchema =
| BBReferenceSingleFieldMetadata | BBReferenceSingleFieldMetadata
| ArrayFieldMetadata | ArrayFieldMetadata
| OptionsFieldMetadata | OptionsFieldMetadata
| BooleanFieldMetadata
| BigIntFieldMetadata
export interface TableSchema { export interface TableSchema {
[key: string]: FieldSchema [key: string]: FieldSchema