Dataset Viewer
Auto-converted to Parquet Duplicate
hash
stringlengths
40
40
date
stringdate
2020-04-14 18:04:14
2025-03-25 16:48:49
author
stringclasses
154 values
commit_message
stringlengths
15
172
is_merge
bool
1 class
masked_commit_message
stringlengths
11
165
type
stringclasses
7 values
git_diff
stringlengths
32
8.56M
12283892dcf0edf0b8692584650ab24ad35df600
2023-11-20 14:59:48
sharanya-appsmith
test: Cypress - skipping flaky cases in ce (#28959)
false
Cypress - skipping flaky cases in ce (#28959)
test
diff --git a/app/client/cypress/e2e/Regression/ClientSide/Git/GitSync/GitSyncedApps_spec.js b/app/client/cypress/e2e/Regression/ClientSide/Git/GitSync/GitSyncedApps_spec.js index 2451d218f0e3..421dc7640abe 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Git/GitSync/GitSyncedApps_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/Git/GitSync/GitSyncedApps_spec.js @@ -27,7 +27,7 @@ const mainBranch = "master"; let datasourceName; let repoName; -describe("Git sync apps", function () { +describe.skip("Git sync apps", function () { before(() => { // homePage.NavigateToHome(); // cy.createWorkspace(); diff --git a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Modal/Modal_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Modal/Modal_spec.ts index 03c8b6a42b68..f60d2107bdf6 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Modal/Modal_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Modal/Modal_spec.ts @@ -10,7 +10,7 @@ import { table, } from "../../../../../support/Objects/ObjectsCore"; -describe("Modal Widget test cases", function () { +describe.skip("Modal Widget test cases", function () { const image = (src: string) => 'img[src="' + src + '"]'; const jpgImg = "https://jpeg.org/images/jpegsystems-home.jpg"; const gifImg =
2214abc1bf2d93d7df220e91c3179f24b746353a
2023-11-20 09:26:45
Manish Kumar
fix: modified error code for unauthorised trigger and execute calls (#28946)
false
modified error code for unauthorised trigger and execute calls (#28946)
fix
diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginError.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginError.java index 802f01623524..9f5b575b81ef 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginError.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginError.java @@ -107,6 +107,15 @@ public enum AppsmithPluginError implements BasePluginError { ErrorType.AUTHENTICATION_ERROR, "{0}", "{1}"), + PLUGIN_DATASOURCE_AUTHENTICATION_ERROR( + 400, + AppsmithPluginErrorCode.PLUGIN_DATASOURCE_AUTHENTICATION_ERROR.getCode(), + "Invalid authentication credentials. Please check datasource configuration.", + AppsmithErrorAction.DEFAULT, + "Datasource authentication error", + ErrorType.DATASOURCE_CONFIGURATION_ERROR, + "{0}", + "{1}"), PLUGIN_DATASOURCE_ERROR( 400, AppsmithPluginErrorCode.PLUGIN_DATASOURCE_ERROR.getCode(), diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginErrorCode.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginErrorCode.java index 7e6465e4ab4a..7e482eefa358 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginErrorCode.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/exceptions/pluginExceptions/AppsmithPluginErrorCode.java @@ -17,6 +17,7 @@ public enum AppsmithPluginErrorCode { PLUGIN_DATASOURCE_TIMEOUT_ERROR("PE-DSE-5004", "Timed out when connecting to datasource"), PLUGIN_QUERY_TIMEOUT_ERROR("PE-QRY-5000", "Timed out on query execution"), PLUGIN_AUTHENTICATION_ERROR("PE-ATH-5000", "Datasource authentication error"), + PLUGIN_DATASOURCE_AUTHENTICATION_ERROR("PE-ATH-4000", "Datasource authentication error"), PLUGIN_DATASOURCE_ERROR("PE-DSE-4000", "Datasource error"), PLUGIN_UQI_WHERE_CONDITION_UNKNOWN("PE-UQI-5000", "Where condition could not be parsed"), GENERIC_STALE_CONNECTION("PE-STC-5000", "Secondary stale connection error"), diff --git a/app/server/appsmith-plugins/openAiPlugin/src/main/java/com/external/plugins/OpenAiPlugin.java b/app/server/appsmith-plugins/openAiPlugin/src/main/java/com/external/plugins/OpenAiPlugin.java index 22acc5f477c6..dc181441e41e 100644 --- a/app/server/appsmith-plugins/openAiPlugin/src/main/java/com/external/plugins/OpenAiPlugin.java +++ b/app/server/appsmith-plugins/openAiPlugin/src/main/java/com/external/plugins/OpenAiPlugin.java @@ -111,8 +111,8 @@ public Mono<ActionExecutionResult> executeCommon( if (HttpStatusCode.valueOf(401).isSameCodeAs(statusCode)) { actionExecutionResult.setIsExecutionSuccess(false); - actionExecutionResult.setErrorInfo( - new AppsmithPluginException(AppsmithPluginError.PLUGIN_AUTHENTICATION_ERROR)); + actionExecutionResult.setErrorInfo(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_DATASOURCE_AUTHENTICATION_ERROR)); return Mono.just(actionExecutionResult); } @@ -183,8 +183,8 @@ public Mono<TriggerResultDTO> trigger( return RequestUtils.makeRequest(httpMethod, uri, bearerTokenAuth, BodyInserters.empty()) .flatMap(responseEntity -> { if (responseEntity.getStatusCode().is4xxClientError()) { - return Mono.error( - new AppsmithPluginException(AppsmithPluginError.PLUGIN_AUTHENTICATION_ERROR)); + return Mono.error(new AppsmithPluginException( + AppsmithPluginError.PLUGIN_DATASOURCE_AUTHENTICATION_ERROR)); } if (!responseEntity.getStatusCode().is2xxSuccessful()) { @@ -237,12 +237,13 @@ public Mono<DatasourceTestResult> testDatasource(DatasourceConfiguration datasou } AppsmithPluginException error = - new AppsmithPluginException(AppsmithPluginError.PLUGIN_AUTHENTICATION_ERROR); + new AppsmithPluginException(AppsmithPluginError.PLUGIN_DATASOURCE_AUTHENTICATION_ERROR); return new DatasourceTestResult(error.getMessage()); }) .onErrorResume(error -> { if (!(error instanceof AppsmithPluginException)) { - error = new AppsmithPluginException(AppsmithPluginError.PLUGIN_AUTHENTICATION_ERROR); + error = new AppsmithPluginException( + AppsmithPluginError.PLUGIN_DATASOURCE_AUTHENTICATION_ERROR); } return Mono.just(new DatasourceTestResult(error.getMessage())); });
c8792b1bae39896d10ea50994c783a191b9aa6ae
2023-08-10 19:42:19
NandanAnantharamu
test: cypress - updated tests for Tab (#26210)
false
cypress - updated tests for Tab (#26210)
test
diff --git a/app/client/cypress/e2e/Regression/ClientSide/DynamicHeight/Text_With_Different_Size_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/DynamicHeight/Text_With_Different_Size_spec.ts index c23976e81bd9..93379bb44ecd 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/DynamicHeight/Text_With_Different_Size_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/DynamicHeight/Text_With_Different_Size_spec.ts @@ -8,8 +8,9 @@ import { describe("Dynamic Height Width validation", function () { function validateCssProperties(property) { agHelper.GetNClickByContains("button", "Small", 0, true); - agHelper.Sleep(3000); + agHelper.Sleep(2000); entityExplorer.SelectEntityByName("Text1"); + agHelper.Sleep(2000); agHelper .GetWidgetCSSFrAttribute( locators._widgetInDeployed(draggableWidgets.TEXT), @@ -26,6 +27,7 @@ describe("Dynamic Height Width validation", function () { ) .then((CurrentValueOfSecondText) => { entityExplorer.SelectEntityByName("Text3"); + agHelper.Sleep(2000); agHelper .GetWidgetCSSFrAttribute( locators._widgetInDeployed(draggableWidgets.TEXT), @@ -34,6 +36,7 @@ describe("Dynamic Height Width validation", function () { ) .then((CurrentValueOfThirdText) => { entityExplorer.SelectEntityByName("Text4"); + agHelper.Sleep(2000); agHelper .GetWidgetCSSFrAttribute( locators._widgetInDeployed(draggableWidgets.TEXT), @@ -120,8 +123,9 @@ describe("Dynamic Height Width validation", function () { 0, true, ); - agHelper.Sleep(3000); + agHelper.Sleep(2000); entityExplorer.SelectEntityByName("Text1"); + agHelper.Sleep(2000); agHelper .GetWidgetCSSFrAttribute( locators._widgetInDeployed( @@ -147,6 +151,7 @@ describe("Dynamic Height Width validation", function () { entityExplorer.SelectEntityByName( "Text3", ); + agHelper.Sleep(2000); agHelper .GetWidgetCSSFrAttribute( locators._widgetInDeployed( @@ -162,6 +167,7 @@ describe("Dynamic Height Width validation", function () { entityExplorer.SelectEntityByName( "Text4", ); + agHelper.Sleep(2000); agHelper .GetWidgetCSSFrAttribute( locators._widgetInDeployed( diff --git a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Tab/Tab_spec.js b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Tab/Tab_spec.js index 559dd8538c38..eb2f7a2deaea 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Tab/Tab_spec.js +++ b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Tab/Tab_spec.js @@ -2,11 +2,15 @@ const commonlocators = require("../../../../../locators/commonlocators.json"); const Layoutpage = require("../../../../../locators/Layout.json"); const widgetsPage = require("../../../../../locators/Widgets.json"); const publish = require("../../../../../locators/publishWidgetspage.json"); -import * as _ from "../../../../../support/Objects/ObjectsCore"; +import { + agHelper, + deployMode, + propPane, +} from "../../../../../support/Objects/ObjectsCore"; describe("Tab widget test", function () { before(() => { - _.agHelper.AddDsl("layoutdsl"); + agHelper.AddDsl("layoutdsl"); }); it("1. Tab Widget Functionality Test", function () { cy.openPropertyPane("tabswidget"); @@ -45,7 +49,7 @@ describe("Tab widget test", function () { .scrollIntoView({ easing: "linear" }) .should("be.visible"); cy.assertPageSave(); - _.deployMode.DeployApp(); + deployMode.DeployApp(); }); it("2. Tab Widget Functionality To Select Tabs", function () { @@ -54,23 +58,23 @@ describe("Tab widget test", function () { .last() .click({ force: true }) .should("have.class", "is-selected"); - _.deployMode.NavigateBacktoEditor(); + deployMode.NavigateBacktoEditor(); }); it("3. Tab Widget Functionality To Unchecked Visible Widget", function () { cy.openPropertyPane("tabswidget"); cy.togglebarDisable(commonlocators.visibleCheckbox); - _.deployMode.DeployApp(); + deployMode.DeployApp(); cy.get(publish.tabWidget).should("not.exist"); - _.deployMode.NavigateBacktoEditor(); + deployMode.NavigateBacktoEditor(); }); it("4. Tab Widget Functionality To Check Visible Widget", function () { cy.openPropertyPane("tabswidget"); cy.togglebar(commonlocators.visibleCheckbox); - _.deployMode.DeployApp(); + deployMode.DeployApp(); cy.get(publish.tabWidget).should("be.visible"); - _.deployMode.NavigateBacktoEditor(); + deployMode.NavigateBacktoEditor(); }); it("5. Tab Widget Functionality To Check tab invisiblity", function () { @@ -80,9 +84,9 @@ describe("Tab widget test", function () { }); cy.get(Layoutpage.tabVisibility).first().click({ force: true }); cy.get(Layoutpage.tabWidget).contains("Tab 1").should("not.exist"); - _.deployMode.DeployApp(); + deployMode.DeployApp(); cy.get(publish.tabWidget).contains("Tab 1").should("not.exist"); - _.deployMode.NavigateBacktoEditor(); + deployMode.NavigateBacktoEditor(); }); it("6. Tab Widget Functionality To Check tab visibility", function () { @@ -92,9 +96,9 @@ describe("Tab widget test", function () { }); cy.get(Layoutpage.tabVisibility).first().click({ force: true }); cy.get(Layoutpage.tabWidget).contains("Tab 1").should("be.visible"); - _.deployMode.DeployApp(); + deployMode.DeployApp(); cy.get(publish.tabWidget).contains("Tab 1").should("be.visible"); - _.deployMode.NavigateBacktoEditor(); + deployMode.NavigateBacktoEditor(); }); /* Test to be revisted as the undo action is inconsistent in automation it("7. Tab Widget Functionality To Check undo action after delete", function() { @@ -115,7 +119,7 @@ describe("Tab widget test", function () { cy.get(Layoutpage.tabWidget) .contains("Tab 1") .should("be.visible"); - _.deployMode.DeployApp(); + deployMode.DeployApp(); cy.get(publish.tabWidget) .contains("Tab 1") .should("be.visible"); @@ -129,8 +133,8 @@ describe("Tab widget test", function () { cy.openPropertyPane("tabswidget"); // Add a new tab - cy.get(Layoutpage.tabButton).last().click({ force: true }); - cy.get(Layoutpage.tabButton).last().click({ force: true }); + agHelper.ClickButton("Add tab"); + agHelper.ClickButton("Add tab"); cy.tabVerify(3, "Tab3-for-testing-scroll-navigation-controls"); // Should show off right navigation arrow cy.get(leftNavButtonSelector).should("exist"); @@ -141,7 +145,7 @@ describe("Tab widget test", function () { }); it("8. Tab Widget Functionality To Check Default Tab selected After Selected Tab Delete", function () { - cy.testJsontext("defaulttab", "Tab 2"); + propPane.UpdatePropertyFieldValue("Default tab", "Tab 1"); cy.tabVerify(3, "Tab3-for-testing-scroll-navigation-controls"); cy.get(Layoutpage.tabWidget) .contains("Tab3-for-testing-scroll-navigation-controls") @@ -153,19 +157,20 @@ describe("Tab widget test", function () { ), ).click({ force: true }); cy.get(Layoutpage.tabWidget) - .contains("Tab 2") + .contains("Tab 1") .should("have.class", "is-selected"); }); it("9. Tab Widget Functionality To Check First Tab Selected After Selected Tab(Default one) Delete", function () { - cy.get(Layoutpage.tabDelete).eq(2).click({ force: true }); + cy.get(Layoutpage.tabDelete).eq(1).click({ force: true }); + cy.wait(1000); cy.get(Layoutpage.tabWidget) .contains("Aditya") .should("have.class", "is-selected"); // Validates Total Number Of Tabs Displayed In The Property Pane cy.get(Layoutpage.tabNumber).should("have.text", "2"); // Validates Total Number Of Tabs Displayed In The Property Pane After Adding A Tab - cy.get(Layoutpage.tabButton).last().click({ force: true }); + agHelper.ClickButton("Add tab"); cy.get(Layoutpage.tabNumber).should("have.text", "3"); //Validates Total Number Of Tabs Displayed In The Property Pane After Deleting A Tab cy.get(Layoutpage.tabDelete).eq(1).click({ force: true });
6ea32b1d8d67f2d9db35d6be5f0e3bbdbe02a29e
2023-06-02 18:08:50
tkAppsmith
fix: added gitsyncid assignment to DataSource constructor with dataSourceS… (#23912)
false
added gitsyncid assignment to DataSource constructor with dataSourceS… (#23912)
fix
diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ActionDTO.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ActionDTO.java index 7ad24f140a06..a4e824b57452 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ActionDTO.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/ActionDTO.java @@ -192,6 +192,7 @@ public void sanitiseToExportDBObject() { this.setCacheResponse(null); if (this.getDatasource() != null) { this.getDatasource().setCreatedAt(null); + this.getDatasource().setDatasourceStorages(null); } if (this.getUserPermissions() != null) { this.getUserPermissions().clear(); diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Datasource.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Datasource.java index 7366e0f4e59a..30a89648a314 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Datasource.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/Datasource.java @@ -124,6 +124,7 @@ public Datasource(DatasourceStorage datasourceStorage) { this.isRecentlyCreated = datasourceStorage.getIsRecentlyCreated(); this.isTemplate = datasourceStorage.getIsTemplate(); this.isMock = datasourceStorage.getIsMock(); + this.gitSyncId = datasourceStorage.getGitSyncId(); HashMap<String, DatasourceStorageDTO> storages = new HashMap<>(); this.datasourceStorages = storages; diff --git a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceStorage.java b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceStorage.java index deb092e34f04..05f9678bfe3a 100644 --- a/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceStorage.java +++ b/app/server/appsmith-interfaces/src/main/java/com/appsmith/external/models/DatasourceStorage.java @@ -42,6 +42,12 @@ public class DatasourceStorage extends BaseDomain { @JsonView(Views.Public.class) Set<String> invalids = new HashSet<>(); + @Transient + String name; + + @Transient + String pluginId; + /* * - To return useful hints to the user. * - These messages are generated by the API server based on the other datasource attributes. @@ -51,12 +57,6 @@ public class DatasourceStorage extends BaseDomain { @JsonView(Views.Public.class) Set<String> messages = new HashSet<>(); - @Transient - String name; - - @Transient - String pluginId; - @Transient String pluginName; @@ -162,5 +162,6 @@ public void sanitiseToExportResource(Map<String, String> pluginMap) { this.setId(null); this.setWorkspaceId(null); this.setPluginId(pluginMap.get(this.getPluginId())); + this.setIsRecentlyCreated(null); } }
ce787752777575a22cbebd2cf5fbaf962d6afec5
2023-08-16 18:28:45
Anagh Hegde
chore: Analytics file lock stale time (#26276)
false
Analytics file lock stale time (#26276)
chore
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ce/FieldNameCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ce/FieldNameCE.java index 1099acd76bd1..6292e0b310b4 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ce/FieldNameCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/constants/ce/FieldNameCE.java @@ -185,4 +185,6 @@ public class FieldNameCE { public static final String GIT_HOSTING_PROVIDER = "gitHostingProvider"; public static final String IS_MERGEABLE = "isMergeable"; + + public static final String FILE_LOCK_DURATION = "fileLockDuration"; } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/GlobalExceptionHandler.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/GlobalExceptionHandler.java index 832144592ca1..d0b79fbbafda 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/GlobalExceptionHandler.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/GlobalExceptionHandler.java @@ -339,6 +339,7 @@ private Mono<Boolean> deleteLockFileAndSendAnalytics(File file, String urlPath) analyticsProps.put(FieldName.APPLICATION_ID, appId); } if (!fileTime.equals(0L)) { + analyticsProps.put(FieldName.FILE_LOCK_DURATION, fileTime); return sessionUserService .getCurrentUser() .flatMap(user -> analyticsService.sendEvent( diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GitServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GitServiceCEImpl.java index b883fa8c65f3..de5573640f84 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GitServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/GitServiceCEImpl.java @@ -2236,7 +2236,7 @@ public Mono<MergeStatusDTO> isBranchMergeable(String defaultApplicationId, GitMe .getGitApplicationMetadata() .getIsRepoPrivate(), false, - true)) + mergeStatusDTO.isMergeAble())) .then(Mono.just(mergeStatusDTO)))) .onErrorResume(error -> { try {
f7e69f59848adf73fb85bf7634785858c7ba8faf
2022-09-13 13:14:06
Trisha Anand
chore: Added username to error logs when signup is disabled (#16720)
false
Added username to error logs when signup is disabled (#16720)
chore
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppsmithError.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppsmithError.java index 975b9b064d27..78d679ccc07a 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppsmithError.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/exceptions/AppsmithError.java @@ -111,7 +111,7 @@ public enum AppsmithError { MARKETPLACE_NOT_CONFIGURED(500, 5007, "Marketplace is not configured.", AppsmithErrorAction.DEFAULT, null, ErrorType.CONFIGURATION_ERROR, null), PAYLOAD_TOO_LARGE(413, 4028, "The request payload is too large. Max allowed size for request payload is {0} KB", AppsmithErrorAction.DEFAULT, null, ErrorType.CONNECTIVITY_ERROR, null), - SIGNUP_DISABLED(403, 4033, "Signup is restricted on this instance of Appsmith. Please contact the administrator to get an invite.", + SIGNUP_DISABLED(403, 4033, "Signup is restricted on this instance of Appsmith. Please contact the administrator to get an invite for user {0}.", AppsmithErrorAction.DEFAULT, null, ErrorType.INTERNAL_ERROR, null), FAIL_UPDATE_USER_IN_SESSION(500, 5008, "Unable to update user in session.", AppsmithErrorAction.LOG_EXTERNALLY, null, ErrorType.INTERNAL_ERROR, null), APPLICATION_FORKING_NOT_ALLOWED(403, 4034, "Forking this application is not permitted at this time.", AppsmithErrorAction.DEFAULT, null, ErrorType.INTERNAL_ERROR, null), diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserServiceCEImpl.java index 7aa65d24d906..c8c2cf014ccb 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/services/ce/UserServiceCEImpl.java @@ -534,7 +534,7 @@ private Mono<User> signupIfAllowed(User user) { if (commonConfig.isSignupDisabled()) { // Signing up has been globally disabled. Reject. - return Mono.error(new AppsmithException(AppsmithError.SIGNUP_DISABLED)); + return Mono.error(new AppsmithException(AppsmithError.SIGNUP_DISABLED, user.getUsername())); } final List<String> allowedDomains = user.getSource() == LoginSource.FORM @@ -546,7 +546,7 @@ private Mono<User> signupIfAllowed(User user) { && !allowedDomains.contains(user.getEmail().split("@")[1])) { // There is an explicit whitelist of email address domains that should be allowed. If the new email is // of a different domain, reject. - return Mono.error(new AppsmithException(AppsmithError.SIGNUP_DISABLED)); + return Mono.error(new AppsmithException(AppsmithError.SIGNUP_DISABLED, user.getUsername())); } } else { isAdminUser = true;
efc704b94ea818fe603afedc51b7942db8f88785
2023-10-06 15:05:08
NandanAnantharamu
test: fix for tabs2 spec (#27854)
false
fix for tabs2 spec (#27854)
test
diff --git a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Tab/Tabs_2_spec.ts b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Tab/Tabs_2_spec.ts index e6f7360f30aa..eeca97b3f6dd 100644 --- a/app/client/cypress/e2e/Regression/ClientSide/Widgets/Tab/Tabs_2_spec.ts +++ b/app/client/cypress/e2e/Regression/ClientSide/Widgets/Tab/Tabs_2_spec.ts @@ -6,6 +6,7 @@ import { propPane, table, tabs, + assertHelper, } from "../../../../../support/Objects/ObjectsCore"; describe("Tabs widget Tests", function () { @@ -205,6 +206,7 @@ describe("Tabs widget Tests", function () { // Border Color propPane.SelectColorFromColorPicker("bordercolor", 13); + assertHelper.AssertNetworkStatus("@updateLayout"); agHelper.AssertCSS( tabs._tabsWidgetStyle, "border-color", @@ -221,6 +223,7 @@ describe("Tabs widget Tests", function () { // Verify Box Shadow agHelper.GetNClick(`${propPane._segmentedControl("0")}:contains('Large')`); + assertHelper.AssertNetworkStatus("@updateLayout"); agHelper.AssertCSS( tabs._tabsWidgetStyle, "box-shadow",
cc36ae70bbd5104d927f107cd5cd50c4182fc1e3
2022-07-04 14:33:31
Bhavin K
fix: revert checkbox-group widget breaking UI issue (#14933)
false
revert checkbox-group widget breaking UI issue (#14933)
fix
diff --git a/app/client/src/widgets/CheckboxGroupWidget/component/index.tsx b/app/client/src/widgets/CheckboxGroupWidget/component/index.tsx index a3657b984eb3..2830f891b327 100644 --- a/app/client/src/widgets/CheckboxGroupWidget/component/index.tsx +++ b/app/client/src/widgets/CheckboxGroupWidget/component/index.tsx @@ -69,15 +69,6 @@ export interface CheckboxGroupContainerProps { export const CheckboxGroupContainer = styled.div<CheckboxGroupContainerProps>` ${labelLayoutStyles} - justify-content: ${({ compactMode, labelPosition }) => { - if ( - labelPosition && - labelPosition !== LabelPosition.Left && - !compactMode - ) { - return "flex-start"; - } - }}; & .${LABEL_CONTAINER_CLASS} { ${({ labelPosition }) => labelPosition === LabelPosition.Left && "min-height: 30px"}; diff --git a/app/client/src/widgets/CheckboxGroupWidget/widget/index.tsx b/app/client/src/widgets/CheckboxGroupWidget/widget/index.tsx index ae5024495d63..4451cb6b8cad 100644 --- a/app/client/src/widgets/CheckboxGroupWidget/widget/index.tsx +++ b/app/client/src/widgets/CheckboxGroupWidget/widget/index.tsx @@ -165,29 +165,9 @@ class CheckboxGroupWidget extends BaseWidget< isJSConvertible: true, isBindProperty: true, isTriggerProperty: false, - updateHook: ( - props: CheckboxGroupWidgetProps, - propertyPath: string, - propertyValue: string, - ) => { - const propertiesToUpdate = [{ propertyPath, propertyValue }]; - const isOffInline = - typeof propertyValue === "string" - ? !(propertyValue === "true") - : !propertyValue; - - if (isOffInline) { - propertiesToUpdate.push({ - propertyPath: "optionAlignment", - propertyValue: CheckboxGroupAlignmentTypes.NONE, - }); - } - return propertiesToUpdate; - }, validation: { type: ValidationTypes.BOOLEAN, }, - dependencies: ["isInline"], }, { propertyName: "isSelectAll", @@ -335,12 +315,6 @@ class CheckboxGroupWidget extends BaseWidget< ], }, }, - hidden: (props: CheckboxGroupWidgetProps) => { - return typeof props.isInline === "string" - ? !(props.isInline === "true") - : !props.isInline; - }, - dependencies: ["isInline"], }, { propertyName: "labelTextColor",
1688757bc634dbf76eae30bb68300fec09ed382d
2022-03-04 11:56:12
Ankita Kinger
fix: Signup text update & code optimisation (#11606)
false
Signup text update & code optimisation (#11606)
fix
diff --git a/app/client/jest.config.js b/app/client/jest.config.js index bae9af532c91..478bea0b291f 100644 --- a/app/client/jest.config.js +++ b/app/client/jest.config.js @@ -44,6 +44,7 @@ module.exports = { enableGithubOAuth: parseConfig("__APPSMITH_OAUTH2_GITHUB_CLIENT_ID__"), disableLoginForm: parseConfig("__APPSMITH_FORM_LOGIN_DISABLED__"), disableSignup: parseConfig("__APPSMITH_SIGNUP_DISABLED__"), + disableTelemetry: parseConfig("__APPSMITH_DISABLE_TELEMETRY__"), enableRapidAPI: parseConfig("__APPSMITH_MARKETPLACE_ENABLED__"), segment: { apiKey: parseConfig("__APPSMITH_SEGMENT_KEY__"), diff --git a/app/client/public/index.html b/app/client/public/index.html index 3cedce33ae4f..0fd4b0143470 100755 --- a/app/client/public/index.html +++ b/app/client/public/index.html @@ -195,6 +195,7 @@ enableGithubOAuth: parseConfig("__APPSMITH_OAUTH2_GITHUB_CLIENT_ID__"), disableLoginForm: parseConfig("__APPSMITH_FORM_LOGIN_DISABLED__"), disableSignup: parseConfig("__APPSMITH_SIGNUP_DISABLED__"), + disableTelemetry: parseConfig("__APPSMITH_DISABLE_TELEMETRY__"), enableRapidAPI: parseConfig("__APPSMITH_MARKETPLACE_ENABLED__"), segment: { apiKey: parseConfig("__APPSMITH_SEGMENT_KEY__"), diff --git a/app/client/src/ce/configs/index.ts b/app/client/src/ce/configs/index.ts index 5200a0d2699b..8a6750bab9ae 100644 --- a/app/client/src/ce/configs/index.ts +++ b/app/client/src/ce/configs/index.ts @@ -17,6 +17,7 @@ export interface INJECTED_CONFIGS { enableGithubOAuth: boolean; disableLoginForm: boolean; disableSignup: boolean; + disableTelemetry: boolean; enableRapidAPI: boolean; segment: { apiKey: string; @@ -77,6 +78,9 @@ export const getConfigsFromEnvVars = (): INJECTED_CONFIGS => { disableSignup: process.env.APPSMITH_SIGNUP_DISABLED ? process.env.APPSMITH_SIGNUP_DISABLED.length > 0 : false, + disableTelemetry: process.env.APPSMITH_DISABLE_TELEMETRY + ? process.env.APPSMITH_DISABLE_TELEMETRY.length > 0 + : true, segment: { apiKey: process.env.REACT_APP_SEGMENT_KEY || "", ceKey: process.env.REACT_APP_SEGMENT_CE_KEY || "", @@ -246,6 +250,8 @@ export const getAppsmithConfigs = (): AppsmithUIConfigs => { ENV_CONFIG.disableLoginForm || APPSMITH_FEATURE_CONFIGS.disableLoginForm, disableSignup: ENV_CONFIG.disableSignup || APPSMITH_FEATURE_CONFIGS.disableSignup, + disableTelemetry: + ENV_CONFIG.disableTelemetry || APPSMITH_FEATURE_CONFIGS.disableTelemetry, enableGoogleOAuth: ENV_CONFIG.enableGoogleOAuth || APPSMITH_FEATURE_CONFIGS.enableGoogleOAuth, diff --git a/app/client/src/ce/configs/types.ts b/app/client/src/ce/configs/types.ts index 51bf7e7c6a31..7eac1a47da30 100644 --- a/app/client/src/ce/configs/types.ts +++ b/app/client/src/ce/configs/types.ts @@ -46,6 +46,7 @@ export interface AppsmithUIConfigs { enableGithubOAuth: boolean; disableLoginForm: boolean; disableSignup: boolean; + disableTelemetry: boolean; enableMixpanel: boolean; enableTNCPP: boolean; diff --git a/app/client/src/ce/pages/AdminSettings/config/authentication/index.tsx b/app/client/src/ce/pages/AdminSettings/config/authentication/index.tsx index 951d865820a7..19c3d897a11b 100644 --- a/app/client/src/ce/pages/AdminSettings/config/authentication/index.tsx +++ b/app/client/src/ce/pages/AdminSettings/config/authentication/index.tsx @@ -6,6 +6,7 @@ import { } from "constants/ThirdPartyConstants"; import { SettingCategories, + SettingSubCategories, SettingTypes, SettingSubtype, AdminConfigType, @@ -34,7 +35,7 @@ const Form_Auth: AdminConfigType = { { id: "APPSMITH_FORM_LOGIN_DISABLED", category: SettingCategories.FORM_AUTH, - subCategory: "form login", + subCategory: SettingSubCategories.FORMLOGIN, controlType: SettingTypes.TOGGLE, label: "Form Login Option", toggleText: (value: boolean) => { @@ -48,12 +49,12 @@ const Form_Auth: AdminConfigType = { { id: "APPSMITH_SIGNUP_DISABLED", category: SettingCategories.FORM_AUTH, - subCategory: "form signup", + subCategory: SettingSubCategories.FORMLOGIN, controlType: SettingTypes.TOGGLE, label: "Signup", toggleText: (value: boolean) => { if (value) { - return "Allow only invited users to signup"; + return "Restrict Signups"; } else { return " Allow all users to signup"; } @@ -62,7 +63,7 @@ const Form_Auth: AdminConfigType = { { id: "APPSMITH_FORM_CALLOUT_BANNER", category: SettingCategories.FORM_AUTH, - subCategory: "form signup", + subCategory: SettingSubCategories.FORMLOGIN, controlType: SettingTypes.LINK, label: "User emails are not verified. This can lead to a breach in your application.", @@ -83,7 +84,7 @@ const Google_Auth: AdminConfigType = { { id: "APPSMITH_OAUTH2_GOOGLE_READ_MORE", category: SettingCategories.GOOGLE_AUTH, - subCategory: "google signup", + subCategory: SettingSubCategories.GOOGLE, controlType: SettingTypes.LINK, label: "How to configure?", url: GOOGLE_SIGNUP_SETUP_DOC, @@ -91,7 +92,7 @@ const Google_Auth: AdminConfigType = { { id: "APPSMITH_OAUTH2_GOOGLE_CLIENT_ID", category: SettingCategories.GOOGLE_AUTH, - subCategory: "google signup", + subCategory: SettingSubCategories.GOOGLE, controlType: SettingTypes.TEXTINPUT, controlSubType: SettingSubtype.TEXT, label: "Client ID", @@ -99,7 +100,7 @@ const Google_Auth: AdminConfigType = { { id: "APPSMITH_OAUTH2_GOOGLE_CLIENT_SECRET", category: SettingCategories.GOOGLE_AUTH, - subCategory: "google signup", + subCategory: SettingSubCategories.GOOGLE, controlType: SettingTypes.TEXTINPUT, controlSubType: SettingSubtype.TEXT, label: "Client Secret", @@ -107,7 +108,7 @@ const Google_Auth: AdminConfigType = { { id: "APPSMITH_SIGNUP_ALLOWED_DOMAINS", category: SettingCategories.GOOGLE_AUTH, - subCategory: "google signup", + subCategory: SettingSubCategories.GOOGLE, controlType: SettingTypes.TEXTINPUT, controlSubType: SettingSubtype.TEXT, label: "Allowed Domains", @@ -128,7 +129,7 @@ const Github_Auth: AdminConfigType = { { id: "APPSMITH_OAUTH2_GITHUB_READ_MORE", category: SettingCategories.GITHUB_AUTH, - subCategory: "github signup", + subCategory: SettingSubCategories.GITHUB, controlType: SettingTypes.LINK, label: "How to configure?", url: GITHUB_SIGNUP_SETUP_DOC, @@ -136,7 +137,7 @@ const Github_Auth: AdminConfigType = { { id: "APPSMITH_OAUTH2_GITHUB_CLIENT_ID", category: SettingCategories.GITHUB_AUTH, - subCategory: "github signup", + subCategory: SettingSubCategories.GITHUB, controlType: SettingTypes.TEXTINPUT, controlSubType: SettingSubtype.TEXT, label: "Client ID", @@ -144,7 +145,7 @@ const Github_Auth: AdminConfigType = { { id: "APPSMITH_OAUTH2_GITHUB_CLIENT_SECRET", category: SettingCategories.GITHUB_AUTH, - subCategory: "github signup", + subCategory: SettingSubCategories.GITHUB, controlType: SettingTypes.TEXTINPUT, controlSubType: SettingSubtype.TEXT, label: "Client Secret", diff --git a/app/client/src/ce/pages/AdminSettings/config/types.ts b/app/client/src/ce/pages/AdminSettings/config/types.ts index 859a8776ab84..869a5663d3e3 100644 --- a/app/client/src/ce/pages/AdminSettings/config/types.ts +++ b/app/client/src/ce/pages/AdminSettings/config/types.ts @@ -71,6 +71,12 @@ export const SettingCategories = { GITHUB_AUTH: "github-auth", }; +export const SettingSubCategories = { + GOOGLE: "google signup", + GITHUB: "github signup", + FORMLOGIN: "form login", +}; + export type AdminConfigType = { type: string; controlType: SettingTypes; diff --git a/app/client/src/ce/utils/adminSettingsHelpers.ts b/app/client/src/ce/utils/adminSettingsHelpers.ts index 6a83b7000b43..04b97c286270 100644 --- a/app/client/src/ce/utils/adminSettingsHelpers.ts +++ b/app/client/src/ce/utils/adminSettingsHelpers.ts @@ -11,18 +11,21 @@ export const connectedMethods = [ !disableLoginForm, ].filter(Boolean); +/* settings is the updated & unsaved settings on Admin settings page */ export const saveAllowed = (settings: any) => { - if ( - connectedMethods.length >= 2 || - (connectedMethods.length === 1 && - ((!("APPSMITH_FORM_LOGIN_DISABLED" in settings) && !disableLoginForm) || - (settings["APPSMITH_OAUTH2_GOOGLE_CLIENT_ID"] !== "" && - enableGoogleOAuth) || - (settings["APPSMITH_OAUTH2_GITHUB_CLIENT_ID"] !== "" && - enableGithubOAuth))) - ) { - return true; + if (connectedMethods.length === 1) { + const checkFormLogin = !( + "APPSMITH_FORM_LOGIN_DISABLED" in settings || disableLoginForm + ), + checkGoogleAuth = + settings["APPSMITH_OAUTH2_GOOGLE_CLIENT_ID"] !== "" && + enableGoogleOAuth, + checkGithubAuth = + settings["APPSMITH_OAUTH2_GITHUB_CLIENT_ID"] !== "" && + enableGithubOAuth; + + return checkFormLogin || checkGoogleAuth || checkGithubAuth; } else { - return false; + return connectedMethods.length >= 2; } }; diff --git a/app/client/src/pages/Settings/FormGroup/TextInput.tsx b/app/client/src/pages/Settings/FormGroup/TextInput.tsx index ae37172c6cce..4dfce25bc22b 100644 --- a/app/client/src/pages/Settings/FormGroup/TextInput.tsx +++ b/app/client/src/pages/Settings/FormGroup/TextInput.tsx @@ -6,7 +6,8 @@ import { FormGroup, SettingComponentProps } from "./Common"; export default function TextInput({ setting }: SettingComponentProps) { return ( <FormGroup - className={`t--admin-settings-text-input t--admin-settings-${setting.name}`} + className={`t--admin-settings-text-input t--admin-settings-${setting.name || + setting.id}`} setting={setting} > <FormTextField diff --git a/app/client/src/pages/Settings/SettingsForm.tsx b/app/client/src/pages/Settings/SettingsForm.tsx index 1fa91b547ed2..0feca1feaf63 100644 --- a/app/client/src/pages/Settings/SettingsForm.tsx +++ b/app/client/src/pages/Settings/SettingsForm.tsx @@ -193,9 +193,9 @@ export function SettingsForm( const validate = (values: Record<string, any>) => { const errors: any = {}; _.filter(values, (value, name) => { - const message = AdminConfig.validate(name, value); - if (message) { - errors[name] = message; + const err_message = AdminConfig.validate(name, value); + if (err_message) { + errors[name] = err_message; } }); return errors; diff --git a/app/client/src/pages/Settings/config/advanced.ts b/app/client/src/pages/Settings/config/advanced.ts index 323c424785f6..907a1cac0169 100644 --- a/app/client/src/pages/Settings/config/advanced.ts +++ b/app/client/src/pages/Settings/config/advanced.ts @@ -12,7 +12,7 @@ export const config: AdminConfigType = { settings: [ { id: "APPSMITH_MONGODB_URI", - category: "advanced", + category: SettingCategories.ADVANCED, controlType: SettingTypes.TEXTINPUT, controlSubType: SettingSubtype.TEXT, label: "MongoDB URI", @@ -21,7 +21,7 @@ export const config: AdminConfigType = { }, { id: "APPSMITH_REDIS_URL", - category: "advanced", + category: SettingCategories.ADVANCED, controlType: SettingTypes.TEXTINPUT, controlSubType: SettingSubtype.TEXT, label: "Redis URL", @@ -30,7 +30,7 @@ export const config: AdminConfigType = { }, { id: "APPSMITH_CUSTOM_DOMAIN", - category: "advanced", + category: SettingCategories.ADVANCED, controlType: SettingTypes.TEXTINPUT, controlSubType: SettingSubtype.TEXT, label: "Custom Domain", diff --git a/app/client/src/pages/Settings/config/email.ts b/app/client/src/pages/Settings/config/email.ts index ff638f4028e1..aa4b37fb3ecc 100644 --- a/app/client/src/pages/Settings/config/email.ts +++ b/app/client/src/pages/Settings/config/email.ts @@ -21,14 +21,14 @@ export const config: AdminConfigType = { settings: [ { id: "APPSMITH_MAIL_READ_MORE", - category: "email", + category: SettingCategories.EMAIL, controlType: SettingTypes.LINK, label: "How to configure?", url: EMAIL_SETUP_DOC, }, { id: "APPSMITH_MAIL_HOST", - category: "email", + category: SettingCategories.EMAIL, controlType: SettingTypes.TEXTINPUT, controlSubType: SettingSubtype.TEXT, label: "SMTP Host", @@ -36,7 +36,7 @@ export const config: AdminConfigType = { }, { id: "APPSMITH_MAIL_PORT", - category: "email", + category: SettingCategories.EMAIL, controlType: SettingTypes.TEXTINPUT, controlSubType: SettingSubtype.NUMBER, placeholder: "25", @@ -50,7 +50,7 @@ export const config: AdminConfigType = { }, { id: "APPSMITH_MAIL_FROM", - category: "email", + category: SettingCategories.EMAIL, controlType: SettingTypes.TEXTINPUT, controlSubType: SettingSubtype.TEXT, label: "From Address", @@ -65,13 +65,13 @@ export const config: AdminConfigType = { }, { id: "APPSMITH_MAIL_SMTP_TLS_ENABLED", - category: "email", + category: SettingCategories.EMAIL, controlType: SettingTypes.TOGGLE, label: "TLS Protected Connection", }, { id: "APPSMITH_MAIL_USERNAME", - category: "email", + category: SettingCategories.EMAIL, controlType: SettingTypes.TEXTINPUT, controlSubType: SettingSubtype.TEXT, label: "SMTP Username", @@ -81,7 +81,7 @@ export const config: AdminConfigType = { }, { id: "APPSMITH_MAIL_PASSWORD", - category: "email", + category: SettingCategories.EMAIL, controlType: SettingTypes.TEXTINPUT, controlSubType: SettingSubtype.PASSWORD, label: "SMTP Password", @@ -91,7 +91,7 @@ export const config: AdminConfigType = { }, { id: "APPSMITH_MAIL_TEST_EMAIL", - category: "email", + category: SettingCategories.EMAIL, action: (dispatch: Dispatch<ReduxAction<any>>, settings: any = {}) => { dispatch && dispatch({ diff --git a/app/client/src/pages/Settings/config/general.ts b/app/client/src/pages/Settings/config/general.ts index 6138fe1ed1de..15c2053cb85d 100644 --- a/app/client/src/pages/Settings/config/general.ts +++ b/app/client/src/pages/Settings/config/general.ts @@ -16,7 +16,7 @@ export const config: AdminConfigType = { settings: [ { id: "APPSMITH_INSTANCE_NAME", - category: "general", + category: SettingCategories.GENERAL, controlType: SettingTypes.TEXTINPUT, controlSubType: SettingSubtype.TEXT, label: "Instance Name", @@ -24,7 +24,7 @@ export const config: AdminConfigType = { }, { id: "APPSMITH_ADMIN_EMAILS", - category: "general", + category: SettingCategories.GENERAL, controlType: SettingTypes.TEXTINPUT, controlSubType: SettingSubtype.EMAIL, label: "Admin Email", @@ -51,14 +51,14 @@ export const config: AdminConfigType = { "_blank", ); }, - category: "general", + category: SettingCategories.GENERAL, controlType: SettingTypes.BUTTON, label: "Generated Docker Compose File", text: "Download", }, { id: "APPSMITH_DISABLE_TELEMETRY", - category: "general", + category: SettingCategories.GENERAL, controlType: SettingTypes.TOGGLE, label: "Disable Sharing Anonymous Usage Data", subText: "Share anonymous usage data to help improve the product", @@ -66,7 +66,7 @@ export const config: AdminConfigType = { if (value) { return "Don't share any data"; } else { - return "Share data & make appsmith better!"; + return "Share Anonymous Telemetry"; } }, }, diff --git a/app/client/src/pages/Settings/config/googleMaps.ts b/app/client/src/pages/Settings/config/googleMaps.ts index 365bd5b5322a..8601ece8b3ec 100644 --- a/app/client/src/pages/Settings/config/googleMaps.ts +++ b/app/client/src/pages/Settings/config/googleMaps.ts @@ -14,14 +14,14 @@ export const config: AdminConfigType = { settings: [ { id: "APPSMITH_GOOGLE_MAPS_READ_MORE", - category: "google-maps", + category: SettingCategories.GOOGLE_MAPS, controlType: SettingTypes.LINK, label: "How to configure?", url: GOOGLE_MAPS_SETUP_DOC, }, { id: "APPSMITH_GOOGLE_MAPS_API_KEY", - category: "google-maps", + category: SettingCategories.GOOGLE_MAPS, controlType: SettingTypes.TEXTINPUT, controlSubType: SettingSubtype.TEXT, label: "Google Maps API Key", diff --git a/app/client/src/pages/Settings/config/version.ts b/app/client/src/pages/Settings/config/version.ts index 36d84ec6f0cb..6abe20c91cf9 100644 --- a/app/client/src/pages/Settings/config/version.ts +++ b/app/client/src/pages/Settings/config/version.ts @@ -14,7 +14,7 @@ export const config: AdminConfigType = { settings: [ { id: "APPSMITH_CURRENT_VERSION", - category: "version", + category: SettingCategories.VERSION, controlType: SettingTypes.TEXT, label: "Current version", }, @@ -27,7 +27,7 @@ export const config: AdminConfigType = { payload: true, }); }, - category: "version", + category: SettingCategories.VERSION, controlType: SettingTypes.LINK, label: "Release Notes", }, diff --git a/app/client/src/sagas/SuperUserSagas.tsx b/app/client/src/sagas/SuperUserSagas.tsx index 9239a0f89b4f..29a00fb414b6 100644 --- a/app/client/src/sagas/SuperUserSagas.tsx +++ b/app/client/src/sagas/SuperUserSagas.tsx @@ -133,7 +133,7 @@ function* SendTestEmail(action: ReduxAction<SendTestEmailPayload>) { }); } catch (e) { Toaster.show({ - text: createMessage(TEST_EMAIL_FAILURE), + text: e?.message || createMessage(TEST_EMAIL_FAILURE), hideProgressBar: true, variant: Variant.danger, });
396922e260d804f3ba0ae538b7bb94b3198d40ef
2022-07-01 16:53:34
Pawan Kumar
fix: Updates border radius and box shadow labels in widgets (#14948)
false
Updates border radius and box shadow labels in widgets (#14948)
fix
diff --git a/app/client/src/constants/ThemeConstants.tsx b/app/client/src/constants/ThemeConstants.tsx index c02fa4862bb0..3980e6578afe 100644 --- a/app/client/src/constants/ThemeConstants.tsx +++ b/app/client/src/constants/ThemeConstants.tsx @@ -122,8 +122,8 @@ export const borderRadiusPropertyName = "borderRadius"; */ export const borderRadiusOptions: Record<string, string> = { none: "0px", - md: "0.375rem", - lg: "1.5rem", + M: "0.375rem", + L: "1.5rem", }; export const boxShadowPropertyName = "boxShadow"; @@ -133,9 +133,9 @@ export const boxShadowPropertyName = "boxShadow"; */ export const boxShadowOptions: Record<string, string> = { none: "none", - sm: "0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)", - md: "0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)", - lg: "0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)", + S: "0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06)", + M: "0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)", + L: "0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)", }; export const colorsPropertyName = "colors";
bb55029f42f548efcda3c1d931ca9aac79199bd8
2020-08-24 16:20:50
Abhinav Jha
fix: Missing form button (#397)
false
Missing form button (#397)
fix
diff --git a/app/client/src/icons/WidgetIcons.tsx b/app/client/src/icons/WidgetIcons.tsx index 41e31c193c30..e4c85b4f7114 100644 --- a/app/client/src/icons/WidgetIcons.tsx +++ b/app/client/src/icons/WidgetIcons.tsx @@ -125,6 +125,11 @@ export const WidgetIcons: { <ModalIcon /> </IconWrapper> ), + FORM_BUTTON_WIDGET: (props: IconProps) => ( + <IconWrapper {...props}> + <ButtonIcon /> + </IconWrapper> + ), }; export type WidgetIcon = typeof WidgetIcons[keyof typeof WidgetIcons];
d06477afafcd53af251ccd1b4c2c8d7ed3e59dbb
2024-08-02 12:22:03
Nidhi
fix: Do not return composed action collections after refactor (#35350)
false
Do not return composed action collections after refactor (#35350)
fix
diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/actioncollections/base/ActionCollectionServiceCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/actioncollections/base/ActionCollectionServiceCE.java index b048168c81b3..7f44a12aea7b 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/actioncollections/base/ActionCollectionServiceCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/actioncollections/base/ActionCollectionServiceCE.java @@ -40,7 +40,8 @@ Mono<ActionCollectionDTO> populateActionCollectionByViewMode( Mono<ActionCollectionDTO> splitValidActionsByViewMode( ActionCollectionDTO actionCollectionDTO, List<ActionDTO> actionsList, Boolean viewMode); - Flux<ActionCollectionDTO> getActionCollectionsByViewMode(MultiValueMap<String, String> params, Boolean viewMode); + Flux<ActionCollectionDTO> getNonComposedActionCollectionsByViewMode( + MultiValueMap<String, String> params, Boolean viewMode); Mono<ActionCollectionDTO> update(String id, ActionCollectionDTO actionCollectionDTO); diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/actioncollections/base/ActionCollectionServiceCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/actioncollections/base/ActionCollectionServiceCEImpl.java index 49635f17a093..b7d369ef7242 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/actioncollections/base/ActionCollectionServiceCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/actioncollections/base/ActionCollectionServiceCEImpl.java @@ -130,7 +130,7 @@ public Mono<ActionCollection> findByBaseIdAndBranchName(String id, String branch @Override public Flux<ActionCollectionDTO> getPopulatedActionCollectionsByViewMode( MultiValueMap<String, String> params, Boolean viewMode) { - return this.getActionCollectionsByViewMode(params, viewMode) + return this.getNonComposedActionCollectionsByViewMode(params, viewMode) .flatMap(actionCollectionDTO -> this.populateActionCollectionByViewMode(actionCollectionDTO, viewMode)); } @@ -187,7 +187,7 @@ public Flux<ActionCollectionViewDTO> getActionCollectionsForViewMode(String appl return applicationService .findBranchedApplicationId(branchName, applicationId, applicationPermission.getReadPermission()) .flatMapMany(branchedApplicationId -> repository - .findByApplicationIdAndViewMode( + .findNonComposedByApplicationIdAndViewMode( branchedApplicationId, true, actionPermission.getExecutePermission()) .flatMap(this::generateActionCollectionViewDTO)); } @@ -195,7 +195,8 @@ public Flux<ActionCollectionViewDTO> getActionCollectionsForViewMode(String appl @Override public Flux<ActionCollectionViewDTO> getActionCollectionsForViewMode(String branchedApplicationId) { return repository - .findByApplicationIdAndViewMode(branchedApplicationId, true, actionPermission.getExecutePermission()) + .findNonComposedByApplicationIdAndViewMode( + branchedApplicationId, true, actionPermission.getExecutePermission()) .flatMap(this::generateActionCollectionViewDTO); } @@ -235,16 +236,16 @@ protected Mono<ActionCollectionViewDTO> generateActionCollectionViewDTO( } @Override - public Flux<ActionCollectionDTO> getActionCollectionsByViewMode( + public Flux<ActionCollectionDTO> getNonComposedActionCollectionsByViewMode( MultiValueMap<String, String> params, Boolean viewMode) { if (params == null || viewMode == null) { return Flux.empty(); } - return getActionCollectionsFromRepoByViewMode(params, viewMode) + return getNonComposedActionCollectionsFromRepoByViewMode(params, viewMode) .flatMap(actionCollection -> generateActionCollectionByViewMode(actionCollection, viewMode)); } - protected Flux<ActionCollection> getActionCollectionsFromRepoByViewMode( + protected Flux<ActionCollection> getNonComposedActionCollectionsFromRepoByViewMode( MultiValueMap<String, String> params, Boolean viewMode) { if (params.getFirst(FieldName.APPLICATION_ID) != null) { // Fetch unpublished pages because GET actions is only called during edit mode. For view mode, different @@ -254,7 +255,7 @@ protected Flux<ActionCollection> getActionCollectionsFromRepoByViewMode( params.getFirst(FieldName.BRANCH_NAME), params.getFirst(FieldName.APPLICATION_ID), applicationPermission.getReadPermission()) - .flatMapMany(childApplicationId -> repository.findByApplicationIdAndViewMode( + .flatMapMany(childApplicationId -> repository.findNonComposedByApplicationIdAndViewMode( childApplicationId, viewMode, actionPermission.getReadPermission())); } String pageId = null; @@ -262,7 +263,7 @@ protected Flux<ActionCollection> getActionCollectionsFromRepoByViewMode( if (params.getFirst(FieldName.PAGE_ID) != null) { pageId = params.getFirst(FieldName.PAGE_ID); } - return repository.findByPageIdAndViewMode(pageId, viewMode, actionPermission.getReadPermission()); + return repository.findAllNonComposedByPageIdAndViewMode(pageId, viewMode, actionPermission.getReadPermission()); } @Override diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomActionCollectionRepositoryCE.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomActionCollectionRepositoryCE.java index 444e8472f913..c7103a988fb8 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomActionCollectionRepositoryCE.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomActionCollectionRepositoryCE.java @@ -18,7 +18,7 @@ public interface CustomActionCollectionRepositoryCE extends AppsmithRepository<A Flux<ActionCollection> findByApplicationId( String applicationId, Optional<AclPermission> aclPermission, Optional<Sort> sort); - Flux<ActionCollection> findByApplicationIdAndViewMode( + Flux<ActionCollection> findNonComposedByApplicationIdAndViewMode( String applicationId, boolean viewMode, AclPermission aclPermission); Flux<ActionCollection> findByPageId(String pageId, AclPermission permission); @@ -39,4 +39,7 @@ Flux<ActionCollection> findAllPublishedActionCollectionsByContextIdAndContextTyp String contextId, CreatorContextType contextType, AclPermission permission); Flux<ActionCollection> findByPageIdAndViewMode(String pageId, boolean viewMode, AclPermission permission); + + Flux<ActionCollection> findAllNonComposedByPageIdAndViewMode( + String pageId, boolean viewMode, AclPermission permission); } diff --git a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomActionCollectionRepositoryCEImpl.java b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomActionCollectionRepositoryCEImpl.java index cce3cc3ff8e4..b47d6751485a 100644 --- a/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomActionCollectionRepositoryCEImpl.java +++ b/app/server/appsmith-server/src/main/java/com/appsmith/server/repositories/ce/CustomActionCollectionRepositoryCEImpl.java @@ -60,7 +60,7 @@ protected BridgeQuery<ActionCollection> getBridgeQueryForFindByApplicationIdAndV } @Override - public Flux<ActionCollection> findByApplicationIdAndViewMode( + public Flux<ActionCollection> findNonComposedByApplicationIdAndViewMode( String applicationId, boolean viewMode, AclPermission aclPermission) { BridgeQuery<ActionCollection> bridgeQuery = getBridgeQueryForFindByApplicationIdAndViewMode(applicationId, viewMode); @@ -138,6 +138,13 @@ public Flux<ActionCollection> findAllPublishedActionCollectionsByContextIdAndCon @Override public Flux<ActionCollection> findByPageIdAndViewMode(String pageId, boolean viewMode, AclPermission permission) { + final BridgeQuery<ActionCollection> query = getActionCollectionsByPageIdAndViewModeQuery(pageId, viewMode); + + return queryBuilder().criteria(query).permission(permission).all(); + } + + protected BridgeQuery<ActionCollection> getActionCollectionsByPageIdAndViewModeQuery( + String pageId, boolean viewMode) { final BridgeQuery<ActionCollection> query = Bridge.query(); if (Boolean.TRUE.equals(viewMode)) { @@ -153,7 +160,12 @@ public Flux<ActionCollection> findByPageIdAndViewMode(String pageId, boolean vie // would exist. To handle this, only fetch non-deleted actions query.isNull(ActionCollection.Fields.unpublishedCollection_deletedAt); } + return query; + } - return queryBuilder().criteria(query).permission(permission).all(); + @Override + public Flux<ActionCollection> findAllNonComposedByPageIdAndViewMode( + String pageId, boolean viewMode, AclPermission permission) { + return this.findByPageIdAndViewMode(pageId, viewMode, permission); } } diff --git a/app/server/appsmith-server/src/test/java/com/appsmith/server/refactors/ce/RefactoringServiceTest.java b/app/server/appsmith-server/src/test/java/com/appsmith/server/refactors/ce/RefactoringServiceTest.java index 12a39821c361..28e8b18141de 100644 --- a/app/server/appsmith-server/src/test/java/com/appsmith/server/refactors/ce/RefactoringServiceTest.java +++ b/app/server/appsmith-server/src/test/java/com/appsmith/server/refactors/ce/RefactoringServiceTest.java @@ -281,7 +281,8 @@ public void jsActionWithoutCollectionIdShouldBeIgnoredDuringNameChecking() { mockActionCollectionDTO.setName("testCollection"); mockActionCollectionDTO.setActions(List.of(firstAction, secondAction)); - Mockito.when(actionCollectionService.getActionCollectionsByViewMode(Mockito.any(), Mockito.anyBoolean())) + Mockito.when(actionCollectionService.getNonComposedActionCollectionsByViewMode( + Mockito.any(), Mockito.anyBoolean())) .thenReturn(Flux.just(mockActionCollectionDTO)); Mono<Boolean> nameAllowedMono = refactoringService.isNameAllowed(
3c688e772bdb60d6a86698ce3cd80eace85c7fea
2023-05-24 11:38:06
Sanveer Singh Osahan
feat: Implemented Schema Fetch for MSSQL Plugin (#16014) (#23498)
false
Implemented Schema Fetch for MSSQL Plugin (#16014) (#23498)
feat
diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/MssqlPlugin.java b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/MssqlPlugin.java index 230c801a4ba9..21ea029b5ab5 100644 --- a/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/MssqlPlugin.java +++ b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/MssqlPlugin.java @@ -11,8 +11,9 @@ import com.appsmith.external.models.ActionConfiguration; import com.appsmith.external.models.ActionExecutionRequest; import com.appsmith.external.models.ActionExecutionResult; -import com.appsmith.external.models.DBAuth; import com.appsmith.external.models.DatasourceConfiguration; +import com.appsmith.external.models.DatasourceStructure; +import com.appsmith.external.models.DBAuth; import com.appsmith.external.models.Endpoint; import com.appsmith.external.models.MustacheBindingToken; import com.appsmith.external.models.Param; @@ -25,14 +26,14 @@ import com.appsmith.external.plugins.SmartSubstitutionInterface; import com.external.plugins.exceptions.MssqlErrorMessages; import com.external.plugins.exceptions.MssqlPluginError; +import com.external.plugins.utils.MssqlDatasourceUtils; +import com.external.plugins.utils.MssqlExecuteUtils; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; -import com.zaxxer.hikari.HikariPoolMXBean; import com.zaxxer.hikari.pool.HikariPool; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; -import org.apache.commons.lang.ObjectUtils; import org.pf4j.Extension; import org.pf4j.PluginWrapper; import org.springframework.util.CollectionUtils; @@ -47,16 +48,13 @@ import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; -import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.sql.Time; import java.sql.Timestamp; import java.sql.Types; +import java.text.MessageFormat; import java.time.Duration; -import java.time.LocalDateTime; -import java.time.OffsetDateTime; -import java.time.format.DateTimeFormatter; import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.HashMap; @@ -68,10 +66,12 @@ import java.util.stream.IntStream; import static com.appsmith.external.constants.ActionConstants.ACTION_CONFIGURATION_BODY; -import static com.appsmith.external.helpers.PluginUtils.getColumnsListForJdbcPlugin; import static com.appsmith.external.helpers.PluginUtils.getIdenticalColumns; import static com.appsmith.external.helpers.PluginUtils.getPSParamLabel; import static com.appsmith.external.helpers.SmartSubstitutionHelper.replaceQuestionMarkWithDollarIndex; +import static com.external.plugins.utils.MssqlDatasourceUtils.getConnectionFromConnectionPool; +import static com.external.plugins.utils.MssqlDatasourceUtils.logHikariCPStatus; +import static com.external.plugins.utils.MssqlExecuteUtils.closeConnectionPostExecution; import static java.lang.Boolean.FALSE; import static java.lang.Boolean.TRUE; @@ -80,8 +80,6 @@ public class MssqlPlugin extends BasePlugin { private static final String JDBC_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; - private static final String DATE_COLUMN_TYPE_NAME = "date"; - private static final int VALIDITY_CHECK_TIMEOUT = 5; private static final int MINIMUM_POOL_SIZE = 5; @@ -102,7 +100,7 @@ public MssqlPlugin(PluginWrapper wrapper) { @Extension public static class MssqlPluginExecutor implements PluginExecutor<HikariDataSource>, SmartSubstitutionInterface { - private final Scheduler scheduler = Schedulers.boundedElastic(); + public static final Scheduler scheduler = Schedulers.boundedElastic(); private static final int PREPARED_STATEMENT_INDEX = 0; @@ -212,14 +210,9 @@ public Mono<ActionExecutionResult> executeCommon(HikariDataSource hikariDSConnec log.error("Error checking validity of MsSQL connection.", error); } - HikariPoolMXBean poolProxy = hikariDSConnection.getHikariPoolMXBean(); - - int idleConnections = poolProxy.getIdleConnections(); - int activeConnections = poolProxy.getActiveConnections(); - int totalConnections = poolProxy.getTotalConnections(); - int threadsAwaitingConnection = poolProxy.getThreadsAwaitingConnection(); - log.debug("Before executing MsSQL query [{}] Hikari Pool stats : active - {} , idle - {} , awaiting - {} , total - {}", - query, activeConnections, idleConnections, threadsAwaitingConnection, totalConnections); + // Log HikariCP status + logHikariCPStatus(MessageFormat.format("Before executing Mssql query [{0}]", query), + hikariDSConnection);; try { if (FALSE.equals(preparedStatement)) { @@ -247,92 +240,18 @@ public Mono<ActionExecutionResult> executeCommon(HikariDataSource hikariDSConnec resultSet = preparedQuery.getResultSet(); } - if (!isResultSet) { - Object updateCount = FALSE.equals(preparedStatement) ? - ObjectUtils.defaultIfNull(statement.getUpdateCount(), 0) : - ObjectUtils.defaultIfNull(preparedQuery.getUpdateCount(), 0); - - rowsList.add(Map.of("affectedRows", updateCount)); - } else { - ResultSetMetaData metaData = resultSet.getMetaData(); - int colCount = metaData.getColumnCount(); - columnsList.addAll(getColumnsListForJdbcPlugin(metaData)); - - while (resultSet.next()) { - // Use `LinkedHashMap` here so that the column ordering is preserved in the response. - Map<String, Object> row = new LinkedHashMap<>(colCount); - - for (int i = 1; i <= colCount; i++) { - Object value; - final String typeName = metaData.getColumnTypeName(i); - - if (resultSet.getObject(i) == null) { - value = null; - - } else if (DATE_COLUMN_TYPE_NAME.equalsIgnoreCase(typeName)) { - value = DateTimeFormatter.ISO_DATE.format(resultSet.getDate(i).toLocalDate()); - - } else if ("timestamp".equalsIgnoreCase(typeName)) { - value = DateTimeFormatter.ISO_DATE_TIME.format( - LocalDateTime.of( - resultSet.getDate(i).toLocalDate(), - resultSet.getTime(i).toLocalTime() - ) - ) + "Z"; - - } else if ("timestamptz".equalsIgnoreCase(typeName)) { - value = DateTimeFormatter.ISO_DATE_TIME.format( - resultSet.getObject(i, OffsetDateTime.class) - ); - - } else if ("time".equalsIgnoreCase(typeName) || "timetz".equalsIgnoreCase(typeName)) { - value = resultSet.getString(i); - - } else if ("interval".equalsIgnoreCase(typeName)) { - value = resultSet.getObject(i).toString(); - - } else { - value = resultSet.getObject(i); - - } - - row.put(metaData.getColumnName(i), value); - } - - rowsList.add(row); - } - - } + MssqlExecuteUtils.populateRowsAndColumns(rowsList, columnsList, resultSet, isResultSet, preparedStatement, + statement, preparedQuery); } catch (SQLException e) { return Mono.error(new AppsmithPluginException(MssqlPluginError.QUERY_EXECUTION_FAILED, MssqlErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, e.getMessage(), "SQLSTATE: "+ e.getSQLState())); } finally { - sqlConnectionFromPool.close(); - if (resultSet != null) { - try { - resultSet.close(); - } catch (SQLException e) { - log.warn("Error closing MsSQL ResultSet", e); - } - } - - if (statement != null) { - try { - statement.close(); - } catch (SQLException e) { - log.warn("Error closing MsSQL Statement", e); - } - } - - if (preparedQuery != null) { - try { - preparedQuery.close(); - } catch (SQLException e) { - log.warn("Error closing MsSQL Statement", e); - } - } + // Log HikariCP status + logHikariCPStatus(MessageFormat.format("After executing Mssql query [{0}]", query), + hikariDSConnection); + closeConnectionPostExecution(resultSet, statement, preparedQuery, sqlConnectionFromPool); } ActionExecutionResult result = new ActionExecutionResult(); @@ -436,6 +355,12 @@ public Mono<ActionExecutionResult> execute(HikariDataSource connection, return Mono.error(new AppsmithPluginException(MssqlPluginError.QUERY_EXECUTION_FAILED, MssqlErrorMessages.QUERY_EXECUTION_FAILED_ERROR_MSG, "Unsupported Operation")); } + @Override + public Mono<DatasourceStructure> getStructure( + HikariDataSource connection, DatasourceConfiguration datasourceConfiguration) { + return MssqlDatasourceUtils.getStructure(connection, datasourceConfiguration); + } + @Override public Object substituteValueInInput(int index, String binding, @@ -631,23 +556,4 @@ private static void addSslOptionsToUrlBuilder(DatasourceConfiguration datasource " Appsmith customer support to resolve this."); } } - - /** - * First checks if the connection pool is still valid. If yes, we fetch a connection from the pool and return - * In case a connection is not available in the pool, SQL Exception is thrown - * - * @param hikariDSConnectionPool - * @return SQL Connection - */ - private static Connection getConnectionFromConnectionPool(HikariDataSource hikariDSConnectionPool) throws SQLException { - - if (hikariDSConnectionPool == null || hikariDSConnectionPool.isClosed() || !hikariDSConnectionPool.isRunning()) { - log.debug("Encountered stale connection pool in SQL Server plugin. Reporting back."); - throw new StaleConnectionException(); - } - - Connection sqlDataSourceConnection = hikariDSConnectionPool.getConnection(); - - return sqlDataSourceConnection; - } } \ No newline at end of file diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/exceptions/MssqlErrorMessages.java b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/exceptions/MssqlErrorMessages.java index de61718f6519..2cb5d2f878c0 100644 --- a/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/exceptions/MssqlErrorMessages.java +++ b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/exceptions/MssqlErrorMessages.java @@ -1,6 +1,7 @@ package com.external.plugins.exceptions; public class MssqlErrorMessages { + private MssqlErrorMessages() { //Prevents instantiation } @@ -13,6 +14,8 @@ private MssqlErrorMessages() { public static final String CONNECTION_POOL_CREATION_FAILED_ERROR_MSG = "Exception occurred while creating connection pool. One or more arguments in the datasource configuration may be invalid. Please check your datasource configuration."; + public static final String GET_STRUCTURE_ERROR_MSG = "The Appsmith server has failed to fetch the structure of your schema."; + /* ************************************************************************************************************************************************ Error messages related to validation of datasource. diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/utils/MssqlDatasourceUtils.java b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/utils/MssqlDatasourceUtils.java new file mode 100644 index 000000000000..d02e7874ba6c --- /dev/null +++ b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/utils/MssqlDatasourceUtils.java @@ -0,0 +1,308 @@ +package com.external.plugins.utils; + +import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginError; +import com.appsmith.external.exceptions.pluginExceptions.AppsmithPluginException; +import com.appsmith.external.exceptions.pluginExceptions.StaleConnectionException; +import com.appsmith.external.models.DatasourceConfiguration; +import com.appsmith.external.models.DatasourceStructure; +import com.external.plugins.exceptions.MssqlErrorMessages; +import com.zaxxer.hikari.HikariDataSource; +import com.zaxxer.hikari.HikariPoolMXBean; +import lombok.AccessLevel; +import lombok.NoArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import reactor.core.publisher.Mono; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static com.appsmith.external.helpers.PluginUtils.safelyCloseSingleConnectionFromHikariCP; +import static com.external.plugins.MssqlPlugin.MssqlPluginExecutor.scheduler; + +@Slf4j +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public class MssqlDatasourceUtils { + + public static final String PRIMARY_KEY_INDICATOR = "PRIMARY KEY"; + + /** + * Example output: + * + * <pre> + * +------------+-----------+---------------+-------------+ + * | TABLE_NAME | COLUMN_NAME | COLUMN_TYPE | SCHEMA_NAME | + * +------------+-----------+---------------+-------------+ + * | CLUB | ID | NUMBER | DBO | + * | STUDENTS | NAME | VARCHAR2 | DBO | + * +------------+-----------+--------------+--------------+ + * </pre> + */ + private static final String QUERY_TO_GET_ALL_TABLE_COLUMN_TYPE = "SELECT \n" + + " col.name AS column_name,\n" + + " typ.name AS column_type,\n" + + " tbl.name AS table_name,\n" + + " sch.name AS schema_name\n" + + "FROM sys.columns col\n" + + " INNER JOIN sys.tables tbl ON col.object_id = tbl.object_id\n" + + " INNER JOIN sys.types typ ON col.user_type_id = typ.user_type_id\n" + + " INNER JOIN sys.schemas sch ON tbl.schema_id = sch.schema_id\n" + + "WHERE tbl.is_ms_shipped = 0\n" + + "ORDER BY tbl.name, col.column_id;\n"; + + + /** + * Example output: + * <pre> + * +------------+-----------+-----------------+-----------------+-------------+ + * | TABLE_NAME |COLUMN_NAME| CONSTRAINT_TYPE | CONSTRAINT_NAME | SCHEMA_NAME | + * +------------+-----------+-----------------+-----------------+-------------+ + * | CLUB | ID | R | FK_STUDENTS_ID | DBO | + * | STUDENTS | ID | P | SYS_C006397 | DBO | + * +------------+-----------+-----------------+-----------------+-------------+ + * </pre> + */ + private static final String QUERY_TO_GET_ALL_TABLE_COLUMN_KEY_CONSTRAINTS = "SELECT \n" + + " cols.table_name,\n" + + " cols.column_name,\n" + + " cols.constraint_schema as schema_name,\n" + + " cons.constraint_type,\n" + + " cons.constraint_name\n" + + "FROM \n" + + " INFORMATION_SCHEMA.KEY_COLUMN_USAGE cols\n" + + " JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS cons\n" + + " ON cols.CONSTRAINT_SCHEMA = cons.CONSTRAINT_SCHEMA\n" + + " AND cols.CONSTRAINT_NAME = cons.CONSTRAINT_NAME\n" + + "WHERE \n" + + " cons.constraint_type IN ('PRIMARY KEY', 'FOREIGN KEY')\n" + + " AND cols.CONSTRAINT_SCHEMA = 'dbo'\n" + + "ORDER BY \n" + + " cols.table_name,\n" + + " cols.ordinal_position\n"; + + public static Mono<DatasourceStructure> getStructure(HikariDataSource connection, DatasourceConfiguration datasourceConfiguration) { + final DatasourceStructure structure = new DatasourceStructure(); + final Map<String, DatasourceStructure.Table> tableNameToTableMap = new LinkedHashMap<>(); + + return Mono.fromSupplier(() -> { + Connection connectionFromPool; + try { + connectionFromPool = getConnectionFromConnectionPool(connection); + } catch (SQLException | StaleConnectionException e) { + // The function can throw either StaleConnectionException or SQLException. The + // underlying hikari library throws SQLException in case the pool is closed or there is an issue + // initializing the connection pool which can also be translated in our world to + // StaleConnectionException and should then trigger the destruction and recreation of the pool. + return Mono.error(e instanceof StaleConnectionException ? e : new StaleConnectionException()); + } + + logHikariCPStatus("Before getting Mssql DB schema", connection); + + try (Statement statement = connectionFromPool.createStatement()) { + // Set table names. For each table set its column names and column types. + setTableNamesAndColumnNamesAndColumnTypes(statement, tableNameToTableMap); + + // Set primary key and foreign key constraints. + setPrimaryAndForeignKeyInfoInTables(statement, tableNameToTableMap); + + } catch (SQLException throwable) { + return Mono.error(new AppsmithPluginException( AppsmithPluginError.PLUGIN_GET_STRUCTURE_ERROR, + MssqlErrorMessages.GET_STRUCTURE_ERROR_MSG, throwable.getCause(), + "SQLSTATE: " + throwable.getSQLState())); + } finally { + logHikariCPStatus("After getting Oracle DB schema", connection); + safelyCloseSingleConnectionFromHikariCP(connectionFromPool, "Error returning Oracle connection to pool " + + "during get structure"); + } + + // Set SQL query templates + setSQLQueryTemplates(tableNameToTableMap); + + structure.setTables(new ArrayList<>(tableNameToTableMap.values())); + log.debug("Got the structure of postgres db"); + return structure; + }) + .map(resultStructure -> (DatasourceStructure) resultStructure) + .subscribeOn(scheduler); + } + + /** + * First checks if the connection pool is still valid. If yes, we fetch a connection from the pool and return + * In case a connection is not available in the pool, SQL Exception is thrown + * + * @param hikariDSConnectionPool + * @return SQL Connection + */ + public static Connection getConnectionFromConnectionPool(HikariDataSource hikariDSConnectionPool) throws SQLException { + + if (hikariDSConnectionPool == null || hikariDSConnectionPool.isClosed() || !hikariDSConnectionPool.isRunning()) { + log.debug("Encountered stale connection pool in SQL Server plugin. Reporting back."); + throw new StaleConnectionException(); + } + + Connection sqlDataSourceConnection = hikariDSConnectionPool.getConnection(); + + return sqlDataSourceConnection; + } + + public static void logHikariCPStatus(String logPrefix, HikariDataSource connectionPool) { + HikariPoolMXBean poolProxy = connectionPool.getHikariPoolMXBean(); + int idleConnections = poolProxy.getIdleConnections(); + int activeConnections = poolProxy.getActiveConnections(); + int totalConnections = poolProxy.getTotalConnections(); + int threadsAwaitingConnection = poolProxy.getThreadsAwaitingConnection(); + log.debug(MessageFormat.format("{0}: Hikari Pool stats : active - {1} , idle - {2}, awaiting - {3} , total - {4}", + logPrefix, activeConnections, idleConnections, threadsAwaitingConnection, totalConnections)); + } + + /** + * Run a SQL query to fetch all tables accessible to user along with their columns and data type of each column. + * Then read the response and populate Appsmith's Table object with the same. + * Please check the SQL query macro definition to find a sample response as comment. + */ + private static void setTableNamesAndColumnNamesAndColumnTypes( + Statement statement, Map<String, DatasourceStructure.Table> tableNameToTableMap) throws SQLException { + try (ResultSet columnsResultSet = statement.executeQuery(QUERY_TO_GET_ALL_TABLE_COLUMN_TYPE)) { + while (columnsResultSet.next()) { + final String columnName = columnsResultSet.getString("column_name"); + final String columnType = columnsResultSet.getString("column_type"); + final String tableName = columnsResultSet.getString("table_name"); + final String schemaName = columnsResultSet.getString("schema_name"); + final String fullTableName = schemaName + "." + tableName; + if (!tableNameToTableMap.containsKey(fullTableName)) { + tableNameToTableMap.put(fullTableName, new DatasourceStructure.Table( + DatasourceStructure.TableType.TABLE, + schemaName, + fullTableName, + new ArrayList<>(), + new ArrayList<>(), + new ArrayList<>())); + } + + final DatasourceStructure.Table table = tableNameToTableMap.get(fullTableName); + + table.getColumns().add( + new DatasourceStructure.Column(columnName, columnType, null, false)); + } + } + } + + /** + * Run a SQL query to fetch all user accessible tables along with their column names and if the column is a + * primary or foreign key. + * Please check the SQL query macro definition to find a sample response as comment. + */ + private static void setPrimaryAndForeignKeyInfoInTables ( + Statement statement, Map<String, DatasourceStructure.Table> tableNameToTableMap) throws SQLException { + Map<String, String> primaryKeyConstraintNameToTableNameMap = new HashMap<>(); + Map<String, String> primaryKeyConstraintNameToColumnNameMap = new HashMap<>(); + Map<String, String> foreignKeyConstraintNameToTableNameMap = new HashMap<>(); + Map<String, String> foreignKeyConstraintNameToColumnNameMap = new HashMap<>(); + try (ResultSet constraintsResultSet = statement.executeQuery(QUERY_TO_GET_ALL_TABLE_COLUMN_KEY_CONSTRAINTS)) { + while (constraintsResultSet.next()) { + final String tableName = constraintsResultSet.getString("table_name"); + final String columnName = constraintsResultSet.getString("column_name"); + final String constraintType = constraintsResultSet.getString("constraint_type"); + final String constraintName = constraintsResultSet.getString("constraint_name"); + final String schemaName = constraintsResultSet.getString("schema_name"); + final String fullTableName = schemaName + "." + tableName; + + if (PRIMARY_KEY_INDICATOR.equalsIgnoreCase(constraintType)) { + primaryKeyConstraintNameToTableNameMap.put(constraintName, fullTableName); + primaryKeyConstraintNameToColumnNameMap.put(constraintName, columnName); + } else { + foreignKeyConstraintNameToTableNameMap.put(constraintName, fullTableName); + foreignKeyConstraintNameToColumnNameMap.put(constraintName, columnName); + } + } + } + + primaryKeyConstraintNameToColumnNameMap.keySet().stream() + .filter(constraintName -> { + String tableName = primaryKeyConstraintNameToTableNameMap.get(constraintName); + return tableNameToTableMap.containsKey(tableName); + }) + .forEach(constraintName -> { + String tableName = primaryKeyConstraintNameToTableNameMap.get(constraintName); + DatasourceStructure.Table table = tableNameToTableMap.get(tableName); + String columnName = primaryKeyConstraintNameToColumnNameMap.get(constraintName); + table.getKeys().add(new DatasourceStructure.PrimaryKey(constraintName, + List.of(columnName))); + }); + + foreignKeyConstraintNameToColumnNameMap.keySet().stream() + .filter(constraintName -> { + String tableName = foreignKeyConstraintNameToTableNameMap.get(constraintName); + return tableNameToTableMap.containsKey(tableName); + }) + .forEach(constraintName -> { + String tableName = foreignKeyConstraintNameToTableNameMap.get(constraintName); + DatasourceStructure.Table table = tableNameToTableMap.get(tableName); + String columnName = foreignKeyConstraintNameToColumnNameMap.get(constraintName); + table.getKeys().add(new DatasourceStructure.ForeignKey(constraintName, + List.of(columnName), new ArrayList<>())); + }); + } + + private static void setSQLQueryTemplates(Map<String, DatasourceStructure.Table> tableNameToTableMap) { + tableNameToTableMap.values() + .forEach(table -> { + LinkedHashMap<String, String> columnNameToSampleColumnDataMap = + new LinkedHashMap<>(); + table.getColumns() + .forEach(column -> columnNameToSampleColumnDataMap.put(column.getName(), + getSampleColumnData(column.getType()))); + + String selectQueryTemplate = MessageFormat.format("SELECT TOP 10 * FROM {0}", table.getName()); + String insertQueryTemplate = MessageFormat.format("INSERT INTO {0} ({1}) " + + "VALUES ({2})", table.getName(), + getSampleColumnNamesCSVString(columnNameToSampleColumnDataMap), + getSampleColumnDataCSVString(columnNameToSampleColumnDataMap)); + String updateQueryTemplate = MessageFormat.format("UPDATE {0} SET {1} WHERE " + + "1=0 -- Specify a valid condition here. Removing the condition may " + + "update every row in the table!", table.getName(), + getSampleOneColumnUpdateString(columnNameToSampleColumnDataMap)); + String deleteQueryTemplate = MessageFormat.format("DELETE FROM {0} WHERE 1=0" + + " -- Specify a valid condition here. Removing the condition may " + + "delete everything in the table!", table.getName()); + + table.getTemplates().add(new DatasourceStructure.Template("SELECT", selectQueryTemplate)); + table.getTemplates().add(new DatasourceStructure.Template("INSERT", insertQueryTemplate)); + table.getTemplates().add(new DatasourceStructure.Template("UPDATE", updateQueryTemplate)); + table.getTemplates().add(new DatasourceStructure.Template("DELETE", deleteQueryTemplate)); + }); + } + + private static String getSampleColumnData(String type) { + if (type == null) { + return "NULL"; + } + + return switch (type.toUpperCase()) { + case "NUMBER", "INT" -> "1"; + case "FLOAT", "DOUBLE" -> "1.0"; + case "CHAR", "NCHAR", "VARCHAR", "VARCHAR2", "NVARCHAR", "NVARCHAR2" -> "'text'"; + default -> "NULL"; + }; + } + + private static String getSampleColumnNamesCSVString(LinkedHashMap<String, String> columnNameToSampleColumnDataMap) { + return String.join(", ", columnNameToSampleColumnDataMap.keySet()); + } + + private static String getSampleColumnDataCSVString(LinkedHashMap<String, String> columnNameToSampleColumnDataMap) { + return String.join(", ", columnNameToSampleColumnDataMap.values()); + } + + private static String getSampleOneColumnUpdateString(LinkedHashMap<String, String> columnNameToSampleColumnDataMap) { + return MessageFormat.format("{0}={1}", columnNameToSampleColumnDataMap.keySet().stream().findFirst().orElse( + "id"), columnNameToSampleColumnDataMap.values().stream().findFirst().orElse("'uid'")); + } +} diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/utils/MssqlExecuteUtils.java b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/utils/MssqlExecuteUtils.java new file mode 100644 index 000000000000..f26a5d1df21b --- /dev/null +++ b/app/server/appsmith-plugins/mssqlPlugin/src/main/java/com/external/plugins/utils/MssqlExecuteUtils.java @@ -0,0 +1,125 @@ +package com.external.plugins.utils; + +import org.apache.commons.lang.ObjectUtils; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSetMetaData; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.text.MessageFormat; +import java.time.LocalDateTime; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static com.appsmith.external.helpers.PluginUtils.getColumnsListForJdbcPlugin; +import static com.appsmith.external.helpers.PluginUtils.safelyCloseSingleConnectionFromHikariCP; +import static java.lang.Boolean.FALSE; + +public class MssqlExecuteUtils { + + private static final String DATE_COLUMN_TYPE_NAME = "date"; + private static final String TIMESTAMP_TYPE_NAME = "timestamp"; + private static final String TIMESTAMPTZ_TYPE_NAME = "timestamptz"; + private static final String TIME_TYPE_NAME = "time"; + private static final String TIMETZ_TYPE_NAME = "timetz"; + private static final String INTERVAL_TYPE_NAME = "interval"; + + + public static void closeConnectionPostExecution(ResultSet resultSet, Statement statement, + PreparedStatement preparedQuery, Connection connectionFromPool) { + if (resultSet != null) { + try { + resultSet.close(); + } catch (SQLException e) { + System.out.println(Thread.currentThread().getName() + + ": Execute Error closing Mssql ResultSet" + e.getMessage()); + } + } + + if (statement != null) { + try { + statement.close(); + } catch (SQLException e) { + System.out.println(Thread.currentThread().getName() + + ": Execute Error closing Mssql Statement" + e.getMessage()); + } + } + + if (preparedQuery != null) { + try { + preparedQuery.close(); + } catch (SQLException e) { + System.out.println(Thread.currentThread().getName() + + ": Execute Error closing Mssql Statement" + e.getMessage()); + } + } + + safelyCloseSingleConnectionFromHikariCP(connectionFromPool, MessageFormat.format("{0}: Execute Error returning " + + "Oracle connection to pool", Thread.currentThread().getName())); + } + + public static void populateRowsAndColumns(List<Map<String, Object>> rowsList, List<String> columnsList, ResultSet resultSet, boolean isResultSet, Boolean preparedStatement, Statement statement, PreparedStatement preparedQuery) throws SQLException { + + if (!isResultSet) { + Object updateCount = FALSE.equals(preparedStatement) ? + ObjectUtils.defaultIfNull(statement.getUpdateCount(), 0) : + ObjectUtils.defaultIfNull(preparedQuery.getUpdateCount(), 0); + + rowsList.add(Map.of("affectedRows", updateCount)); + } else { + ResultSetMetaData metaData = resultSet.getMetaData(); + int colCount = metaData.getColumnCount(); + columnsList.addAll(getColumnsListForJdbcPlugin(metaData)); + + while (resultSet.next()) { + // Use `LinkedHashMap` here so that the column ordering is preserved in the response. + Map<String, Object> row = new LinkedHashMap<>(colCount); + + for (int i = 1; i <= colCount; i++) { + Object value; + final String typeName = metaData.getColumnTypeName(i); + + if (resultSet.getObject(i) == null) { + value = null; + + } else if (DATE_COLUMN_TYPE_NAME.equalsIgnoreCase(typeName)) { + value = DateTimeFormatter.ISO_DATE.format(resultSet.getDate(i).toLocalDate()); + + } else if (TIMESTAMP_TYPE_NAME.equalsIgnoreCase(typeName)) { + value = DateTimeFormatter.ISO_DATE_TIME.format( + LocalDateTime.of( + resultSet.getDate(i).toLocalDate(), + resultSet.getTime(i).toLocalTime() + ) + ) + "Z"; + + } else if (TIMESTAMPTZ_TYPE_NAME.equalsIgnoreCase(typeName)) { + value = DateTimeFormatter.ISO_DATE_TIME.format( + resultSet.getObject(i, OffsetDateTime.class) + ); + + } else if (TIME_TYPE_NAME.equalsIgnoreCase(typeName) || TIMETZ_TYPE_NAME.equalsIgnoreCase(typeName)) { + value = resultSet.getString(i); + + } else if (INTERVAL_TYPE_NAME.equalsIgnoreCase(typeName)) { + value = resultSet.getObject(i).toString(); + + } else { + value = resultSet.getObject(i); + + } + + row.put(metaData.getColumnName(i), value); + } + + rowsList.add(row); + } + + } + } +} diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlGetDBSchemaTest.java b/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlGetDBSchemaTest.java new file mode 100644 index 000000000000..369f7d566204 --- /dev/null +++ b/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlGetDBSchemaTest.java @@ -0,0 +1,159 @@ +package com.external.plugins; + +import com.appsmith.external.models.DatasourceStructure; +import com.zaxxer.hikari.HikariDataSource; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.testcontainers.containers.MSSQLServerContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +import java.sql.SQLException; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +import static com.external.plugins.MssqlTestDBContainerManager.createDatasourceConfiguration; +import static com.external.plugins.MssqlTestDBContainerManager.mssqlPluginExecutor; +import static com.external.plugins.MssqlTestDBContainerManager.runSQLQueryOnMssqlTestDB; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Testcontainers +public class MssqlGetDBSchemaTest { + public static final String SQL_QUERY_TO_CREATE_TABLE_WITH_PRIMARY_KEY = + "CREATE TABLE supplier\n" + + "( supplier_id int not null,\n" + + " supplier_name varchar(50) not null,\n" + + " contact_name varchar(50),\n" + + " CONSTRAINT supplier_pk PRIMARY KEY (supplier_id)\n" + + ")"; + + public static final String SQL_QUERY_TO_CREATE_TABLE_WITH_FOREIGN_KEY = + "CREATE TABLE products\n" + + "( product_id int not null,\n" + + " supplier_id int not null,\n" + + " CONSTRAINT fk_supplier\n" + + " FOREIGN KEY (supplier_id)\n" + + " REFERENCES supplier(supplier_id)\n" + + ")"; + + @SuppressWarnings("rawtypes") // The type parameter for the container type is just itself and is pseudo-optional. + @Container + private static final MSSQLServerContainer container = MssqlTestDBContainerManager.getMssqlDBForTest(); + + private static HikariDataSource sharedConnectionPool = null; + + @BeforeAll + public static void setup() throws SQLException { + sharedConnectionPool = mssqlPluginExecutor.datasourceCreate(createDatasourceConfiguration(container)).block(); + createTablesForTest(); + } + + @Test + public void testDBSchemaShowsAllTables() { + Mono<DatasourceStructure> datasourceStructureMono = + mssqlPluginExecutor.getStructure(sharedConnectionPool, + createDatasourceConfiguration(container)); + + StepVerifier.create(datasourceStructureMono) + .assertNext(datasourceStructure -> { + Set<String> setOfAllTableNames = datasourceStructure.getTables().stream() + .map(DatasourceStructure.Table::getName) + .map(String::toLowerCase) + .collect(Collectors.toSet()); + + assertTrue(setOfAllTableNames.equals(Set.of("dbo.supplier","dbo.products")), setOfAllTableNames.toString()); + }) + .verifyComplete(); + } + + @Test + public void testDBSchemaShowsAllColumnsAndTypesInATable() { + Mono<DatasourceStructure> datasourceStructureMono = + mssqlPluginExecutor.getStructure(sharedConnectionPool, + createDatasourceConfiguration(container)); + + StepVerifier.create(datasourceStructureMono) + .assertNext(datasourceStructure -> { + Optional<DatasourceStructure.Table> supplierTable = datasourceStructure.getTables().stream() + .filter(table -> "dbo.supplier".equalsIgnoreCase(table.getName())) + .findFirst(); + + assertTrue(supplierTable.isPresent(), "supplier table not found in DB schema"); + + Set<String> allColumnNames = supplierTable.get().getColumns().stream() + .map(DatasourceStructure.Column::getName) + .map(String::toLowerCase) + .collect(Collectors.toSet()); + Set<String> expectedColumnNames = Set.of("supplier_id", "supplier_name", "contact_name"); + assertEquals(expectedColumnNames, allColumnNames, allColumnNames.toString()); + + supplierTable.get().getColumns() + .forEach(column -> { + String columnName = column.getName().toLowerCase(); + String columnType = column.getType().toLowerCase(); + String expectedColumnType; + + if ("supplier_id".equals(columnName)) { + expectedColumnType = "int"; + } + else { + expectedColumnType = "varchar"; + } + + assertEquals(expectedColumnType, columnType, columnType); + }); + }) + .verifyComplete(); + } + + @Test + public void testDynamicSqlTemplateQueriesForATable() { + Mono<DatasourceStructure> datasourceStructureMono = + mssqlPluginExecutor.getStructure(sharedConnectionPool, + createDatasourceConfiguration(container)); + + StepVerifier.create(datasourceStructureMono) + .assertNext(datasourceStructure -> { + Optional<DatasourceStructure.Table> supplierTable = datasourceStructure.getTables().stream() + .filter(table -> "dbo.supplier".equalsIgnoreCase(table.getName())) + .findFirst(); + + assertTrue(supplierTable.isPresent(), "supplier table not found in DB schema"); + + supplierTable.get().getTemplates().stream() + .filter(template -> "select".equalsIgnoreCase(template.getTitle()) || "delete".equalsIgnoreCase(template.getTitle())) + .forEach(template -> { + + /* + * Not sure how to test query templates for insert and update queries as these + * queries include column names in an order that is not fixed. Hence, skipping testing + * them for now. + */ + + String expectedQueryTemplate = null; + if ("select".equalsIgnoreCase(template.getTitle())) { + expectedQueryTemplate = "select top 10 * from dbo.supplier"; + } + else if ("delete".equalsIgnoreCase(template.getTitle())) { + expectedQueryTemplate = "delete from dbo.supplier where 1=0 -- specify a valid" + + " condition here. removing the condition may delete everything in the " + + "table!"; + } + + String templateQuery = template.getBody(); + assertEquals(expectedQueryTemplate, templateQuery.toLowerCase(), + templateQuery.toLowerCase()); + }); + }) + .verifyComplete(); + } + + private static void createTablesForTest() throws SQLException { + runSQLQueryOnMssqlTestDB(SQL_QUERY_TO_CREATE_TABLE_WITH_PRIMARY_KEY, sharedConnectionPool); + runSQLQueryOnMssqlTestDB(SQL_QUERY_TO_CREATE_TABLE_WITH_FOREIGN_KEY, sharedConnectionPool); + } +} diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlPluginTest.java b/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlPluginTest.java index 885434cbc749..7735c37c4a1a 100755 --- a/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlPluginTest.java +++ b/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlPluginTest.java @@ -28,14 +28,11 @@ import org.testcontainers.containers.MSSQLServerContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; -import org.testcontainers.utility.DockerImageName; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; -import java.sql.Connection; -import java.sql.DriverManager; import java.sql.SQLException; -import java.sql.Statement; + import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -48,120 +45,67 @@ import java.util.stream.Stream; import static com.appsmith.external.constants.ActionConstants.ACTION_CONFIGURATION_BODY; -import static org.junit.jupiter.api.Assertions.assertArrayEquals; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static com.external.plugins.MssqlTestDBContainerManager.createDatasourceConfiguration; +import static com.external.plugins.MssqlTestDBContainerManager.mssqlPluginExecutor; +import static com.external.plugins.MssqlTestDBContainerManager.runSQLQueryOnMssqlTestDB; +import static org.junit.jupiter.api.Assertions.*; @Testcontainers public class MssqlPluginTest { - MssqlPlugin.MssqlPluginExecutor pluginExecutor = new MssqlPlugin.MssqlPluginExecutor(); - @SuppressWarnings("rawtypes") // The type parameter for the container type is just itself and is pseudo-optional. @Container - public static final MSSQLServerContainer container = - new MSSQLServerContainer<>( - DockerImageName.parse("mcr.microsoft.com/azure-sql-edge:1.0.3").asCompatibleSubstituteFor("mcr.microsoft.com/mssql/server:2017-latest")) - .acceptLicense() - .withExposedPorts(1433) - .withPassword("Mssql123"); - - private static String address; - private static Integer port; - private static String username, password; + public static final MSSQLServerContainer container = MssqlTestDBContainerManager.getMssqlDBForTest(); + + private static HikariDataSource sharedConnectionPool = null; + + private static final String CREATE_USER_TABLE_QUERY = "CREATE TABLE users (\n" + + " id int identity (1, 1) NOT NULL,\n" + + " username VARCHAR (50),\n" + + " password VARCHAR (50),\n" + + " email VARCHAR (355),\n" + + " spouse_dob DATE,\n" + + " dob DATE NOT NULL,\n" + + " time1 TIME NOT NULL,\n" + + " constraint pk_users_id primary key (id)\n" + + ")"; + + private static final String SET_IDENTITY_INSERT_USERS_QUERY = "SET IDENTITY_INSERT users ON;"; + + private static final String INSERT_USER1_QUERY = "INSERT INTO users (id, username, password, email, spouse_dob, dob, time1) VALUES (" + + "1, 'Jack', 'jill', '[email protected]', NULL, '2018-12-31'," + + " '18:32:45'" + + ")"; + + private static final String INSERT_USER2_QUERY = "INSERT INTO users (id, username, password, email, spouse_dob, dob, time1) VALUES (" + + "2, 'Jill', 'jack', '[email protected]', NULL, '2019-12-31'," + + " '15:45:30'" + + ")"; + + private static final String INSERT_USER3_QUERY = "INSERT INTO users (id, username, password, email, spouse_dob, dob, time1) VALUES (" + + "3, 'JackJill', 'jaji', '[email protected]', NULL, '2021-01-31'," + + " '15:45:30'" + + ")"; @BeforeAll public static void setUp() throws SQLException { - address = container.getContainerIpAddress(); - port = container.getMappedPort(1433); - username = container.getUsername(); - password = container.getPassword(); - - try (Connection connection = DriverManager.getConnection( - "jdbc:sqlserver://" + address + ":" + port + ";user=" + username + ";password=" + password + ";trustServerCertificate=true" - )) { - - try (Statement statement = connection.createStatement()) { - statement.execute("CREATE TABLE users (\n" + - " id int identity (1, 1) NOT NULL,\n" + - " username VARCHAR (50),\n" + - " password VARCHAR (50),\n" + - " email VARCHAR (355),\n" + - " spouse_dob DATE,\n" + - " dob DATE NOT NULL,\n" + - " time1 TIME NOT NULL,\n" + - " constraint pk_users_id primary key (id)\n" + - ")"); - - statement.execute("CREATE TABLE possessions (\n" + - " id int identity (1, 1) not null,\n" + - " title VARCHAR (50) NOT NULL,\n" + - " user_id int NOT NULL,\n" + - " constraint pk_possessions_id primary key (id),\n" + - " constraint user_fk foreign key (user_id) references users(id)\n" + - ")"); - } - - try (Statement statement = connection.createStatement()) { - statement.execute("SET identity_insert users ON;"); - } - - try (Statement statement = connection.createStatement()) { - statement.execute( - "INSERT INTO users (id, username, password, email, spouse_dob, dob, time1) VALUES (" + - "1, 'Jack', 'jill', '[email protected]', NULL, '2018-12-31'," + - " '18:32:45'" + - ")"); - } - - try (Statement statement = connection.createStatement()) { - statement.execute( - "INSERT INTO users (id, username, password, email, spouse_dob, dob, time1) VALUES (" + - "2, 'Jill', 'jack', '[email protected]', NULL, '2019-12-31'," + - " '15:45:30'" + - ")"); - } - - try (Statement statement = connection.createStatement()) { - statement.execute( - "INSERT INTO users (id, username, password, email, spouse_dob, dob, time1) VALUES (" + - "3, 'JackJill', 'jaji', '[email protected]', NULL, '2021-01-31'," + - " '15:45:30'" + - ")"); - } - - } + sharedConnectionPool = mssqlPluginExecutor.datasourceCreate(createDatasourceConfiguration(container)).block(); + createTablesForTest(); } - private DatasourceConfiguration createDatasourceConfiguration() { - DBAuth authDTO = new DBAuth(); - authDTO.setAuthType(DBAuth.Type.USERNAME_PASSWORD); - authDTO.setUsername(username); - authDTO.setPassword(password); - - Endpoint endpoint = new Endpoint(); - endpoint.setHost(address); - endpoint.setPort(port.longValue()); - - DatasourceConfiguration dsConfig = new DatasourceConfiguration(); - dsConfig.setAuthentication(authDTO); - dsConfig.setEndpoints(List.of(endpoint)); - - /* set ssl mode */ - dsConfig.setConnection(new com.appsmith.external.models.Connection()); - dsConfig.getConnection().setSsl(new SSLDetails()); - dsConfig.getConnection().getSsl().setAuthType(SSLDetails.AuthType.NO_VERIFY); - - return dsConfig; + private static void createTablesForTest() throws SQLException { + runSQLQueryOnMssqlTestDB(CREATE_USER_TABLE_QUERY, sharedConnectionPool); + runSQLQueryOnMssqlTestDB(SET_IDENTITY_INSERT_USERS_QUERY, sharedConnectionPool); + runSQLQueryOnMssqlTestDB(INSERT_USER1_QUERY, sharedConnectionPool); + runSQLQueryOnMssqlTestDB(INSERT_USER2_QUERY, sharedConnectionPool); + runSQLQueryOnMssqlTestDB(INSERT_USER3_QUERY, sharedConnectionPool); } @Test public void testDefaultPort() { Endpoint endpoint = new Endpoint(); - endpoint.setHost(address); + endpoint.setHost(container.getHost()); long defaultPort = MssqlPlugin.getPort(endpoint); @@ -171,9 +115,9 @@ public void testDefaultPort() { @Test public void testConnectMsSqlContainer() { - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + DatasourceConfiguration dsConfig = createDatasourceConfiguration(container); - Mono<HikariDataSource> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); + Mono<HikariDataSource> dsConnectionMono = mssqlPluginExecutor.datasourceCreate(dsConfig); StepVerifier.create(dsConnectionMono) .assertNext(Assertions::assertNotNull) @@ -182,9 +126,9 @@ public void testConnectMsSqlContainer() { @Test public void testTestDatasource_withCorrectCredentials_returnsWithoutInvalids() { - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + DatasourceConfiguration dsConfig = createDatasourceConfiguration(container); - final Mono<DatasourceTestResult> testDatasourceMono = pluginExecutor.testDatasource(dsConfig); + final Mono<DatasourceTestResult> testDatasourceMono = mssqlPluginExecutor.testDatasource(dsConfig); StepVerifier.create(testDatasourceMono) .assertNext(datasourceTestResult -> { @@ -198,14 +142,14 @@ public void testTestDatasource_withCorrectCredentials_returnsWithoutInvalids() { @Test public void testAliasColumnNames() { - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); - Mono<HikariDataSource> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); + DatasourceConfiguration dsConfig = createDatasourceConfiguration(container); + Mono<HikariDataSource> dsConnectionMono = mssqlPluginExecutor.datasourceCreate(dsConfig); ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setBody("SELECT id as user_id FROM users WHERE id = 1"); Mono<ActionExecutionResult> executeMono = dsConnectionMono - .flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); + .flatMap(conn -> mssqlPluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(result -> { @@ -225,14 +169,14 @@ public void testAliasColumnNames() { @Test public void testExecute() { - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); - Mono<HikariDataSource> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); + DatasourceConfiguration dsConfig = createDatasourceConfiguration(container); + Mono<HikariDataSource> dsConnectionMono = mssqlPluginExecutor.datasourceCreate(dsConfig); ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setBody("SELECT * FROM users WHERE id = 1"); Mono<ActionExecutionResult> executeMono = dsConnectionMono - .flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); + .flatMap(conn -> mssqlPluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(result -> { @@ -277,13 +221,13 @@ public void testExecute() { @Test public void invalidTestConnectMsSqlContainer() { - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + DatasourceConfiguration dsConfig = createDatasourceConfiguration(container); // Set up random username and password and try to connect DBAuth auth = (DBAuth) dsConfig.getAuthentication(); auth.setUsername(new ObjectId().toString()); auth.setPassword(new ObjectId().toString()); - Mono<HikariDataSource> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); + Mono<HikariDataSource> dsConnectionMono = mssqlPluginExecutor.datasourceCreate(dsConfig); StepVerifier.create(dsConnectionMono) .expectErrorMatches(throwable -> throwable instanceof AppsmithPluginException) @@ -292,7 +236,7 @@ public void invalidTestConnectMsSqlContainer() { @Test public void testPreparedStatementWithoutQuotes() { - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + DatasourceConfiguration dsConfig = createDatasourceConfiguration(container); ActionConfiguration actionConfiguration = new ActionConfiguration(); // First test with the binding not surrounded with quotes @@ -311,10 +255,10 @@ public void testPreparedStatementWithoutQuotes() { params.add(param); executeActionDTO.setParams(params); - Mono<HikariDataSource> connectionCreateMono = pluginExecutor.datasourceCreate(dsConfig).cache(); + Mono<HikariDataSource> connectionCreateMono = mssqlPluginExecutor.datasourceCreate(dsConfig).cache(); Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + .flatMap(pool -> mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { @@ -358,7 +302,7 @@ public void testPreparedStatementWithoutQuotes() { @Test public void testPreparedStatementWithDoubleQuotes() { - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + DatasourceConfiguration dsConfig = createDatasourceConfiguration(container); ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setBody("SELECT * FROM users where id = \"{{binding1}}\";"); @@ -376,10 +320,10 @@ public void testPreparedStatementWithDoubleQuotes() { params.add(param); executeActionDTO.setParams(params); - Mono<HikariDataSource> connectionCreateMono = pluginExecutor.datasourceCreate(dsConfig).cache(); + Mono<HikariDataSource> connectionCreateMono = mssqlPluginExecutor.datasourceCreate(dsConfig).cache(); Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + .flatMap(pool -> mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { @@ -433,7 +377,7 @@ public void testPreparedStatementWithDoubleQuotes() { @Test public void testPreparedStatementWithSingleQuotes() { - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + DatasourceConfiguration dsConfig = createDatasourceConfiguration(container); ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setBody("SELECT * FROM users where id = '{{binding1}}';"); @@ -451,10 +395,10 @@ public void testPreparedStatementWithSingleQuotes() { params.add(param); executeActionDTO.setParams(params); - Mono<HikariDataSource> connectionCreateMono = pluginExecutor.datasourceCreate(dsConfig).cache(); + Mono<HikariDataSource> connectionCreateMono = mssqlPluginExecutor.datasourceCreate(dsConfig).cache(); Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + .flatMap(pool -> mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { @@ -491,7 +435,7 @@ public void testPreparedStatementWithSingleQuotes() { @Test public void testPreparedStatementWithNullStringValue() { - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + DatasourceConfiguration dsConfig = createDatasourceConfiguration(container); ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setBody("UPDATE users set " + @@ -513,10 +457,10 @@ public void testPreparedStatementWithNullStringValue() { params.add(param); executeActionDTO.setParams(params); - Mono<HikariDataSource> connectionCreateMono = pluginExecutor.datasourceCreate(dsConfig).cache(); + Mono<HikariDataSource> connectionCreateMono = mssqlPluginExecutor.datasourceCreate(dsConfig).cache(); Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + .flatMap(pool -> mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { @@ -526,7 +470,7 @@ public void testPreparedStatementWithNullStringValue() { actionConfiguration.setBody("SELECT * FROM users where id = 2;"); resultMono = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + .flatMap(pool -> mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { @@ -542,7 +486,7 @@ public void testPreparedStatementWithNullStringValue() { @Test public void testPreparedStatementWithNullValue() { - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + DatasourceConfiguration dsConfig = createDatasourceConfiguration(container); ActionConfiguration actionConfiguration = new ActionConfiguration(); @@ -565,10 +509,10 @@ public void testPreparedStatementWithNullValue() { params.add(param); executeActionDTO.setParams(params); - Mono<HikariDataSource> connectionCreateMono = pluginExecutor.datasourceCreate(dsConfig).cache(); + Mono<HikariDataSource> connectionCreateMono = mssqlPluginExecutor.datasourceCreate(dsConfig).cache(); Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + .flatMap(pool -> mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { @@ -578,7 +522,7 @@ public void testPreparedStatementWithNullValue() { actionConfiguration.setBody("SELECT * FROM users where id = 3;"); resultMono = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + .flatMap(pool -> mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { @@ -594,14 +538,14 @@ public void testPreparedStatementWithNullValue() { @Test public void testDuplicateColumnNames() { - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); - Mono<HikariDataSource> dsConnectionMono = pluginExecutor.datasourceCreate(dsConfig); + DatasourceConfiguration dsConfig = createDatasourceConfiguration(container); + Mono<HikariDataSource> dsConnectionMono = mssqlPluginExecutor.datasourceCreate(dsConfig); ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setBody("SELECT id, username as id, password, email as password FROM users WHERE id = 1"); Mono<ActionExecutionResult> executeMono = dsConnectionMono - .flatMap(conn -> pluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); + .flatMap(conn -> mssqlPluginExecutor.executeParameterized(conn, new ExecuteActionDTO(), dsConfig, actionConfiguration)); StepVerifier.create(executeMono) .assertNext(result -> { @@ -633,7 +577,7 @@ public void testDuplicateColumnNames() { @Test public void testLimitQuery() { - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + DatasourceConfiguration dsConfig = createDatasourceConfiguration(container); ActionConfiguration actionConfiguration = new ActionConfiguration(); // First test with the binding not surrounded with quotes @@ -647,10 +591,10 @@ public void testLimitQuery() { List<Param> params = new ArrayList<>(); executeActionDTO.setParams(params); - Mono<HikariDataSource> connectionCreateMono = pluginExecutor.datasourceCreate(dsConfig).cache(); + Mono<HikariDataSource> connectionCreateMono = mssqlPluginExecutor.datasourceCreate(dsConfig).cache(); Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + .flatMap(pool -> mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { @@ -661,7 +605,7 @@ public void testLimitQuery() { @Test public void testNumericStringHavingLeadingZeroWithPreparedStatement() { - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + DatasourceConfiguration dsConfig = createDatasourceConfiguration(container); ActionConfiguration actionConfiguration = new ActionConfiguration(); actionConfiguration.setBody("SELECT {{binding1}} as numeric_string;"); @@ -679,10 +623,10 @@ public void testNumericStringHavingLeadingZeroWithPreparedStatement() { params.add(param1); executeActionDTO.setParams(params); - Mono<HikariDataSource> connectionCreateMono = pluginExecutor.datasourceCreate(dsConfig).cache(); + Mono<HikariDataSource> connectionCreateMono = mssqlPluginExecutor.datasourceCreate(dsConfig).cache(); Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, + .flatMap(pool -> mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) @@ -736,12 +680,12 @@ public void testSSLNoVerifyConnectionIsEncrypted() { List<Param> params = new ArrayList<>(); executeActionDTO.setParams(params); - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + DatasourceConfiguration dsConfig = createDatasourceConfiguration(container); dsConfig.getConnection().getSsl().setAuthType(SSLDetails.AuthType.NO_VERIFY); - Mono<HikariDataSource> connectionCreateMono = pluginExecutor.datasourceCreate(dsConfig); + Mono<HikariDataSource> connectionCreateMono = mssqlPluginExecutor.datasourceCreate(dsConfig); Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + .flatMap(pool -> mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { @@ -772,12 +716,12 @@ public void testSSLDisabledConnectionIsNotEncrypted() { List<Param> params = new ArrayList<>(); executeActionDTO.setParams(params); - DatasourceConfiguration dsConfig = createDatasourceConfiguration(); + DatasourceConfiguration dsConfig = createDatasourceConfiguration(container); dsConfig.getConnection().getSsl().setAuthType(SSLDetails.AuthType.DISABLE); - Mono<HikariDataSource> connectionCreateMono = pluginExecutor.datasourceCreate(dsConfig); + Mono<HikariDataSource> connectionCreateMono = mssqlPluginExecutor.datasourceCreate(dsConfig); Mono<ActionExecutionResult> resultMono = connectionCreateMono - .flatMap(pool -> pluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); + .flatMap(pool -> mssqlPluginExecutor.executeParameterized(pool, executeActionDTO, dsConfig, actionConfiguration)); StepVerifier.create(resultMono) .assertNext(result -> { diff --git a/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlTestDBContainerManager.java b/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlTestDBContainerManager.java new file mode 100644 index 000000000000..2d6fd3a0ef82 --- /dev/null +++ b/app/server/appsmith-plugins/mssqlPlugin/src/test/java/com/external/plugins/MssqlTestDBContainerManager.java @@ -0,0 +1,64 @@ +package com.external.plugins; + +import com.appsmith.external.models.DBAuth; +import com.appsmith.external.models.DatasourceConfiguration; +import com.appsmith.external.models.Endpoint; +import com.appsmith.external.models.SSLDetails; +import com.zaxxer.hikari.HikariDataSource; +import org.testcontainers.containers.MSSQLServerContainer; +import org.testcontainers.utility.DockerImageName; + +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; + +import static com.external.plugins.utils.MssqlDatasourceUtils.getConnectionFromConnectionPool; +import static com.external.plugins.utils.MssqlExecuteUtils.closeConnectionPostExecution; + +public class MssqlTestDBContainerManager { + + static MssqlPlugin.MssqlPluginExecutor mssqlPluginExecutor = new MssqlPlugin.MssqlPluginExecutor(); + + @SuppressWarnings("rawtypes") + public static MSSQLServerContainer getMssqlDBForTest() { + return new MSSQLServerContainer<>( + DockerImageName.parse("mcr.microsoft.com/azure-sql-edge:1.0.3").asCompatibleSubstituteFor("mcr.microsoft.com/mssql/server:2017-latest")) + .acceptLicense() + .withExposedPorts(1433) + .withPassword("Mssql123"); + } + + static DatasourceConfiguration createDatasourceConfiguration(MSSQLServerContainer container) { + String address = container.getHost(); + Integer port = container.getMappedPort(1433); + String username = container.getUsername(); + String password = container.getPassword(); + + DBAuth authDTO = new DBAuth(); + authDTO.setAuthType(DBAuth.Type.USERNAME_PASSWORD); + authDTO.setUsername(username); + authDTO.setPassword(password); + + Endpoint endpoint = new Endpoint(); + endpoint.setHost(address); + endpoint.setPort(port.longValue()); + + DatasourceConfiguration dsConfig = new DatasourceConfiguration(); + dsConfig.setAuthentication(authDTO); + dsConfig.setEndpoints(List.of(endpoint)); + + /* set ssl mode */ + dsConfig.setConnection(new com.appsmith.external.models.Connection()); + dsConfig.getConnection().setSsl(new SSLDetails()); + dsConfig.getConnection().getSsl().setAuthType(SSLDetails.AuthType.NO_VERIFY); + + return dsConfig; + } + + static void runSQLQueryOnMssqlTestDB(String sqlQuery, HikariDataSource sharedConnectionPool) throws SQLException { + java.sql.Connection connectionFromPool = getConnectionFromConnectionPool(sharedConnectionPool); + Statement statement = connectionFromPool.createStatement(); + statement.execute(sqlQuery); + closeConnectionPostExecution(null, statement, null, connectionFromPool); + } +}
d5bd30202efa8cd35923789603ab3fc36a3ff48d
2025-02-04 12:13:13
Valera Melnikov
fix: move ee utitls (#38986)
false
move ee utitls (#38986)
fix
diff --git a/app/client/packages/utils/src/file/getFileExtension.ts b/app/client/packages/utils/src/file/getFileExtension.ts new file mode 100644 index 000000000000..0610c2ec5031 --- /dev/null +++ b/app/client/packages/utils/src/file/getFileExtension.ts @@ -0,0 +1,9 @@ +/** + * @example + * getFileExtension("file.txt") => "txt" + * getFileExtension("file") => "" + * getFileExtension("file.txt.txt") => "txt" + */ +export const getFileExtension = (fileName: string): string => { + return fileName.split(".").pop() ?? ""; +}; diff --git a/app/client/packages/utils/src/file/getFileName.ts b/app/client/packages/utils/src/file/getFileName.ts new file mode 100644 index 000000000000..a216ddc7e863 --- /dev/null +++ b/app/client/packages/utils/src/file/getFileName.ts @@ -0,0 +1,9 @@ +/** + * @example + * getFileName("file.txt") => "file" + * getFileName("file") => "file" + * getFileName("file.txt.txt") => "file.txt" + */ +export const getFileName = (fileName: string): string => { + return fileName.split(".").slice(0, 1)?.[0] || ""; +}; diff --git a/app/client/packages/utils/src/file/index.ts b/app/client/packages/utils/src/file/index.ts new file mode 100644 index 000000000000..1539c6253b62 --- /dev/null +++ b/app/client/packages/utils/src/file/index.ts @@ -0,0 +1,2 @@ +export { getFileExtension } from "./getFileExtension"; +export { getFileName } from "./getFileName"; diff --git a/app/client/packages/utils/src/index.ts b/app/client/packages/utils/src/index.ts index 442a65511ef1..bde100269226 100644 --- a/app/client/packages/utils/src/index.ts +++ b/app/client/packages/utils/src/index.ts @@ -1,2 +1,5 @@ -export * from "./object"; export * from "./compose"; +export * from "./file"; +export * from "./object"; +export * from "./url"; +export * from "./validateApiPath"; diff --git a/app/client/packages/utils/src/url/buildUrlTextFragment.test.ts b/app/client/packages/utils/src/url/buildUrlTextFragment.test.ts new file mode 100644 index 000000000000..c35ceba7610f --- /dev/null +++ b/app/client/packages/utils/src/url/buildUrlTextFragment.test.ts @@ -0,0 +1,17 @@ +import { buildUrlTextFragment } from "./buildUrlTextFragment"; + +it("should return an empty array if no fragments are provided", () => { + expect(buildUrlTextFragment([])).toEqual(""); +}); + +it("should encode special characters", () => { + expect(buildUrlTextFragment(["text 1 = 2"])).toEqual( + ":~:text=text%201%20%3D%202", + ); +}); + +it("should join fragments", () => { + expect(buildUrlTextFragment(["text 1", "text 2"])).toEqual( + ":~:text=text%201&text=text%202", + ); +}); diff --git a/app/client/packages/utils/src/url/buildUrlTextFragment.ts b/app/client/packages/utils/src/url/buildUrlTextFragment.ts new file mode 100644 index 000000000000..f8a8a7e8eddf --- /dev/null +++ b/app/client/packages/utils/src/url/buildUrlTextFragment.ts @@ -0,0 +1,17 @@ +/** + * @example + * buildUrlTextFragment(["text1"]) // ":~:text=text1" + * buildUrlTextFragment(["text1", "text2"]) // ":~:text=text1&text=text2" + * buildUrlTextFragment([]) // "" + */ +export const buildUrlTextFragment = (fragments: string[]): string => { + if (fragments.length === 0) { + return ""; + } + + const textFragments = fragments + .map(encodeURIComponent) + .map((line) => `text=${line}`); + + return `:~:${textFragments.join("&")}`; +}; diff --git a/app/client/packages/utils/src/url/index.ts b/app/client/packages/utils/src/url/index.ts new file mode 100644 index 000000000000..73ed15204626 --- /dev/null +++ b/app/client/packages/utils/src/url/index.ts @@ -0,0 +1 @@ +export { buildUrlTextFragment } from "./buildUrlTextFragment"; diff --git a/app/client/packages/utils/src/validateApiPath/index.ts b/app/client/packages/utils/src/validateApiPath/index.ts new file mode 100644 index 000000000000..f0ebcab87f1e --- /dev/null +++ b/app/client/packages/utils/src/validateApiPath/index.ts @@ -0,0 +1 @@ +export { validateApiPath } from "./validateApiPath"; diff --git a/app/client/packages/utils/src/validateApiPath/validateApiPath.test.ts b/app/client/packages/utils/src/validateApiPath/validateApiPath.test.ts new file mode 100644 index 000000000000..67d765cb46f3 --- /dev/null +++ b/app/client/packages/utils/src/validateApiPath/validateApiPath.test.ts @@ -0,0 +1,17 @@ +import { validateApiPath } from "./validateApiPath"; + +describe("validateApiPath", () => { + it("should return the path if it starts with 'https://'", () => { + const validPath = "https://example.com"; + + expect(validateApiPath(validPath)).toBe(validPath); + }); + + it("should throw an error if the path does not start with 'https://'", () => { + const invalidPath = "example.com"; + + expect(() => validateApiPath(invalidPath)).toThrow( + "The example.com path must start with 'https://'.", + ); + }); +}); diff --git a/app/client/packages/utils/src/validateApiPath/validateApiPath.ts b/app/client/packages/utils/src/validateApiPath/validateApiPath.ts new file mode 100644 index 000000000000..d84fb93ae995 --- /dev/null +++ b/app/client/packages/utils/src/validateApiPath/validateApiPath.ts @@ -0,0 +1,15 @@ +/** + * Validates if the given path starts with "https://". + * Throws an error if the path does not start with "https://". + * + * @param path - The path to validate. + * @returns path if the path starts with "https://". + * @throws Error if the path does not start with "https://". + */ +export const validateApiPath = (path: string): string => { + if (path.startsWith("https://")) { + return path; + } else { + throw new Error(`The ${path} path must start with 'https://'.`); + } +};
12d1482a477b0e74be9590f464211504cb36b926
2023-09-25 15:36:24
Ankita Kinger
fix: Removing saas integrations section on datasources page for airgap (#27590)
false
Removing saas integrations section on datasources page for airgap (#27590)
fix
diff --git a/app/client/src/pages/Editor/IntegrationEditor/IntegrationsHomeScreen.tsx b/app/client/src/pages/Editor/IntegrationEditor/IntegrationsHomeScreen.tsx index 1367848ced98..de30120d4085 100644 --- a/app/client/src/pages/Editor/IntegrationEditor/IntegrationsHomeScreen.tsx +++ b/app/client/src/pages/Editor/IntegrationEditor/IntegrationsHomeScreen.tsx @@ -37,6 +37,7 @@ import Debugger, { import { showDebuggerFlag } from "selectors/debuggerSelectors"; import AnalyticsUtil from "utils/AnalyticsUtil"; import { DatasourceCreateEntryPoints } from "constants/Datasource"; +import { isAirgapped } from "@appsmith/utils/airgapHelpers"; const HeaderFlex = styled.div` font-size: 20px; @@ -219,6 +220,7 @@ function CreateNewSaasIntegration({ }: any) { const newSaasAPIRef = useRef<HTMLDivElement>(null); const isMounted = useRef(false); + const isAirgappedInstance = isAirgapped(); useEffect(() => { if (active && newSaasAPIRef.current) { @@ -233,7 +235,7 @@ function CreateNewSaasIntegration({ isMounted.current = true; } }, [active]); - return ( + return !isAirgappedInstance ? ( <div id="new-saas-api" ref={newSaasAPIRef}> <Text type={TextType.H2}>Saas Integrations</Text> <NewApiScreen @@ -245,7 +247,7 @@ function CreateNewSaasIntegration({ showUnsupportedPluginDialog={showUnsupportedPluginDialog} /> </div> - ); + ) : null; } function CreateNewDatasource({
de66a50f6c62736732e57e37a38607fd02ce59a4
2023-07-27 16:13:37
Rajat Agrawal
chore: Add property path to WidgetErrors (#25711)
false
Add property path to WidgetErrors (#25711)
chore
diff --git a/app/client/src/utils/widgetRenderUtils.test.ts b/app/client/src/utils/widgetRenderUtils.test.ts index 28ec42779bfe..0737707fb7db 100644 --- a/app/client/src/utils/widgetRenderUtils.test.ts +++ b/app/client/src/utils/widgetRenderUtils.test.ts @@ -41,7 +41,7 @@ describe("createCanvasWidget functionality", () => { const dataTree = { __evaluation__: { errors: { - text: [ + propertyPath: [ { errorMessage: { name: "Validation Error", @@ -64,6 +64,7 @@ describe("createCanvasWidget functionality", () => { expect(response.errors[0].message).toStrictEqual("Error Message"); expect(response.errors[0].stack).toStrictEqual("Error Message Stack"); expect(response.errors[0].type).toStrictEqual("property"); + expect(response.errors[0].path).toStrictEqual("propertyPath"); }); }); diff --git a/app/client/src/utils/widgetRenderUtils.tsx b/app/client/src/utils/widgetRenderUtils.tsx index e35444485db7..985b979a2783 100644 --- a/app/client/src/utils/widgetRenderUtils.tsx +++ b/app/client/src/utils/widgetRenderUtils.tsx @@ -65,19 +65,24 @@ function widgetErrorsFromStaticProps(props: Record<string, unknown>) { string, DataTreeError[] >; - const evaluationErrors: DataTreeError[] = - Object.values(evaluationErrorMap).flat(); const widgetErrors: WidgetError[] = []; - for (const evalError of evaluationErrors) { - const widgetError: WidgetError = { - name: evalError.errorMessage.name, - message: evalError.errorMessage.message, - stack: evalError.raw, - type: "property", - }; - - widgetErrors.push(widgetError); - } + + Object.keys(evaluationErrorMap).forEach((propertyPath) => { + const propertyErrors = evaluationErrorMap[propertyPath]; + + propertyErrors.forEach((evalError) => { + const widgetError: WidgetError = { + name: evalError.errorMessage.name, + message: evalError.errorMessage.message, + stack: evalError.raw, + type: "property", + path: propertyPath, + }; + + widgetErrors.push(widgetError); + }); + }); + return widgetErrors; } diff --git a/app/client/src/widgets/BaseWidget.tsx b/app/client/src/widgets/BaseWidget.tsx index a7d5b777e1ce..67725e2e86c7 100644 --- a/app/client/src/widgets/BaseWidget.tsx +++ b/app/client/src/widgets/BaseWidget.tsx @@ -871,6 +871,7 @@ export const WIDGET_DISPLAY_PROPS = { }; export interface WidgetError extends Error { type: "property" | "configuration" | "other"; + path?: string; } export interface WidgetErrorProps { errors?: WidgetError[];
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
14