Что такое oracle apex
Визуализация данных с помощью Oracle Apex
Oracle Apex – компонент для разработки конечных приложений, входящий в состав поставки СУБД Oracle, позволяющий быстро «доставать» данные из базы и доставлять их через веб-интерфейс конечному пользователю. Как правило, данные для просмотра и редактирования выдаются в табличном виде и Apex предоставляет богатые возможности для настраивания отчета: можно накладывать фильтры, делать сортировку и группировку, скрывать имеющиеся столбцы и добавлять расчетные новые, делать сводные отчеты, выгружать данные в формате csv, pdf и даже Excel. Каждый пользователь может сохранить предпочитаемые им настройки каждого отчета как индивидуально, так и для совместного использования. В таком формате Apex функционирует у большинства наших заказчиков.
Однако мало кто использует довольно широкие возможности Apex’а для построения графиков. Эта тема, на наш взгляд, довольно интересна и мало освещена в интернете.
В этой статье будем предполагать, что читатель имеет представление о разработке приложений с помощью Oracle Apex.
В качестве примера рассмотрим гипотетический дашборд, показывающий переработки и недоработки сотрудников департамента за отчетный период, а также распределение трудозатрат по активностям.
С точки зрения разработки добавление графика на страницу приложения в Apex’е представляет собой добавление региона типа Chart. У него есть ряд обычных для региона свойств, которые можно заполнить значениями по умолчанию или не заполнять вообще.
В интерфейсе разработки Apex 5.1 часть свойств самого региона заполнялась через пункт меню Attributes, что вносило некую неразбериху: было интуитивно не всегда понятно, что и где лежит. Надеюсь, в новых версиях UI эту путаницу убрали. В частности, именно в «атрибутах» указывался тип графика, который мы хотим получить (Рисунок 1). Как видим, выбор достаточно большой и охватывает все основные визуальные представления, используемые аналитиками в большинстве случаев.
Рисунок 1 Выбор типа графика
Здесь же мы указываем ориентацию столбцов гистограммы (вертикальная или горизонтальная), высоту панели, настройку всплывающих подсказок (показывать ли их вообще, а если показывать, то что именно выводить), настройку легенды, а также можем добавить код на JavaScript для тонкой «подгонки» графика под требования заказчика. Это нужно, например, в том случае, если каждому столбцу на диаграмме мы хотим задать цвет на наш выбор. Код можно добавить явно или указать наименование функции, реализацию которой мы можем привести где-то еще (Apex позволяет добавлять в приложение js-файлы для определения кода на «высшем» уровне или указывать код в рамках одной страницы веб-приложения).
В каждом графическом регионе может быть несколько графиков, если они объединены общей осью абсцисс (при этом по оси ординат может быть две шкалы). В таком случае мы добавляем их через пункт меню Series и указываем SQL-запрос, который будет возвращать нам значения по осям и – при желании – некоторую дополнительную информацию: наименование ряда, значения для всплывающих подсказки или даже ссылку для перехода на другую страницу приложения (Рисунок 2). В нашем примере табличный тип данных, возвращаемый запросом, объявлен следующим образом:
Рисунок 2 Настройка графика
Передача параметров (в нашем случае – даты отчета и идентификатора департамента или какого-либо из его подразделений) из формы ввода на сервер происходит стандартным для Apex образом: или через кнопку Submit, или путем создания DynamicAction, который реализует технологию Ajax и может обновить тот или иной регион, их совокупность (ограничения по числу обновляемых регионов нет) на странице динамически. Лично я предпочитаю второй вариант. Изменение графиков при этом происходит в режиме мультфильма: столбцы гистограмм, к примеру, при этом «вырастают» или «съеживаются», появляются стрелки-указатели динамики изменений – пользователь может немного развлечься.
Графики «из коробки» выглядят вполне прилично, но иногда требуется их подстройка под требования заказчика. Например, мой заказчик долгое время получал отчеты в Excel и уже привык к его цветовой гамме, маркерам и т.п. На помощь может прийти JavaScript.
Например, этот код задает цвета для трех вхождений в круговой диаграмме:
Итоговый вид круговой диаграммы приведен на Рисунке 3.
Рисунок 3 Круговая диаграмма Лирическое отступление про цвета
Предположим, например, что нам нужно показать диаграмму распределения трудозатрат по ранее заданному довольно широкому списку активностей. Т.е. активностей много, но в отчетный период заранее неизвестно, работали ли сотрудники над каждой конкретной из них. График строился динамически, поэтому появилась задача подбора цветов для их различения таким образом, что два соседних оттенка довольно контрастно отличались между собой. Выяснилось, что цветов из стандартной поставки буквально не хватает и активности могли начать смешиваться между собой.
Рисунок 4 О цветовой дифференциации – распределение по активностям, в каждой из групп активностей – Co, Ho, Su, могут быть активности из списка над графиком
Почитав пару обсуждений на stackoverflow.com, я решил изобрести свой велосипед следующим образом. Взял таблицу цветов с сайта material design, отсортировал, чтобы близкие группы оттенков (например, «розовый» и «фиолетовый» или «лимонный» и «светло-зеленый») не оказались соседними, какие-то группы цветов исключил и взял только оттенки, которые в css имеют индекс 300, 500, 700 или 900.
В результате получил вот такой список из заведомо избыточных 76 цветов, который и используется в графике (Рисунок 4).
Тех, кому интересна эта тема, могу отправить в обсуждения вот здесь, здесь или здесь.
Надо отметить, что справочных материалов по графикам довольно мало, и настройка через JS может потребовать какое-то время, в первую очередь, на выяснение доступных методов API.
Рисунок 5 Переработка сотрудников какого-то подразделения в феврале какого-то года
Например, для того, чтобы отобразить цифры в кружках на левом графике (см. Рисунок 5), потребовалось сделать настройки для каждого элемента в отдельности:
А референсная линия «0» на правом графике настраивается вот таким кодом:
Мне всё-таки кажется, что подобное вмешательство в установленную функциональность инструмента напоминает костыли. Надеюсь, что в новых версиях Oracle Apex этих «костылей» потребуется меньше. Справедливости ради надо отметить, что в моей практике был случай, когда мне пришлось «допиливать» какие-то настройки BI-отчета с помощью JavaScript в «профессиональном» Oracle BI EE версии 12. На мой взгляд, это говорит о том, что каким бы ни продвинутым инструмент ни был, найдется требование заказчика, выходящее за рамки его штатной функциональности.
В качестве заключения можно сказать, что возможности Oracle Apex как инструмента графического представления данных, конечно, несопоставимы с профессиональными BI-инструментами, особенно если вам потребуется выводить на дашборд что-нибудь вроде линий тренда. Но если вы уже используете БД Oracle, то этими возможностями пренебрегать не стоит. Опять же, с учетом весьма низкого порога входа в эту технологию, она кажется весьма заслуживающей внимания.
Автор статьи: Вадим Бояркин, ведущий консультант группы разработки Big Data Solutions в компании Neoflex
Why Oracle APEX
Oracle APEX has been designed from the very beginning to help developers build modern, beautiful, responsive applications without the need to become specialized experts.
The mission of Oracle APEX is to empower developers to easily build compelling apps with superior functionality, performance, and end user experience. In order to deliver on this mission, Oracle APEX aims to eliminate the enormous complexities of developing and deploying enterprise apps. Here are a few reasons why choosing Oracle APEX makes sense for your next development project.
Eliminating Complexity
Oracle APEX eliminates the complexity of developing and deploying applications at all layers. The result is a low-code platform that is simpler, faster, lighter-weight, and lower-cost than the alternatives.
Simple Development
Oracle APEX is easy to use and easy to learn. The Application Builder provides a rich, browser-based, intuitive interface which guides you through the creation of your applications. The powerful components of Oracle APEX enable you to add a high-level of functionality to your apps with limited coding. Many customers are productive in a week or less!
Powerful and Proven
Secure
Oracle APEX is designed to build web apps which are highly secure out of the box. In a world of ever-changing web standards, evolving security standards, and resourceful hackers, the focus on security means that your applications stay protected and remain state-of-the-art.
Portable
Eliminating Complexity
Low-code application development with Oracle APEX is a whole lot more than simply reducing the amount of code necessary to build incredible applications. Oracle APEX is unique in that it eliminates complexity at all layers.
APEX eliminates mapping between relational and application objects
APEX eliminates remote procedure call complexity
APEX eliminates proliferation of database connections
APEX eliminates middle-tier application logic
APEX eliminates complexity of high availability and disaster recovery
While these complexities are often common when developing applications with other platforms, Oracle APEX eliminates the need for this altogether. Simply put, there is no other platform like it.
Simpler and Faster Development
Oracle APEX is data-driven and development typically begins with a spreadsheet or data model. Applications are developed in a low-code browser-based environment where 98% of hand coding can be eliminated.
Oracle APEX works directly against data in database tables. Most middle-tier apps must define application data structures to hold, convert, interact and maintain data flow between the app to the database. This is a vastly underestimated source of complexity that Oracle APEX completely eliminates.
In addition, APEX eliminates the need and complexity of remote APIs for a large majority of use cases. It is not architected as distributed components, and remote calls to the database are eliminated.
Light-weight and Lower-cost
Having an application run in the database seems heavyweight and expensive, but counterintuitively it is lighter-weight and lower-cost.
When compared to middle-tier applications, running applications on Oracle APEX consumes far fewer resources. Typically, middle-tiers deploy three containers per microservice to achieve High Availability, with each container requiring considerable memory and compute. These applications often make dozens to hundreds of calls to access data in the database to render a single screen. These SQL calls from middle-tier to database are generally 10x slower than when performed directly within the database.
Oracle APEX is both stateless and serverless and the runtime application state is stored in tables so connections can be re-used across users. This results in far fewer connections and each connection is far lighter in weight. In addition, Autoscale on Autonomous Database eliminates the need to manage scaling in middle-tiers. The result is that Oracle APEX apps require less database resources and 100x less mid-tier hardware resources when compared to middle-tier applications.
Easy Deployment
With Oracle APEX, deploying both the app and the data in the database is dramatically simpler when compared to middle-tier applications.
Eliminates complexity of middle-tiers
Everything is in the database. There is no need to design, develop, or manage complex middle tiers.
Eliminates complexity of HA and DR
There is no state in the middle tier, and failover automatically happens within the database
Eliminates complexity of database management
With Oracle Autonomous Database, there is no need for DBA or DevOps to manage your database
Why should I use Oracle APEX?
Developers
Are you an existing Oracle Database customer?
Then you have everything you need to start building useful, scalable apps now using Oracle APEX. If you know even a little bit of SQL, you can become wonderfully productive and start producing apps that you would have thought required a full-stack developer.
Are you an Oracle Forms customer?
With your knowledge of SQL and PL/SQL, you have everything you need to create modern Web applications. Oracle Forms customers readily adapt to the Oracle APEX app dev experience, and as a bonus, you can easily reuse all of your existing SQL and PL/SQL!
Do you work in a line of business? Are you constantly asked to produce solutions, but are given tools which are difficult to learn and use?
Consider Oracle APEX. It’s used for business applications by thousands of customers worldwide, it’s easy to get started, and you have a feature-rich application development environment to build nearly any application you require.
Are you a professional full-stack developer?
Often you will spend most of your time developing and maintaining the “plumbing» required for a typical Web application. The platform of Oracle APEX manages all of the mundane aspects of Web app dev, like security, session state management, concurrency, data persistence, responsive design, and more. Spend more time focusing on your business requirements and less time writing the necessary infrastructure.
Are you an Oracle DBA?
Students
With Oracle APEX, you can easily build web applications with essentially no knowledge of HTML, CSS or JavaScript. Oracle APEX is tightly integrated with Oracle Database and manages all of the processing associated with data manipulation in a database. If you have a basic understanding of SQL, you can build beautiful, responsive web applications very quickly. For data analysis, Oracle APEX is excellent, as it supports the full SQL language, which is the industry standard for data manipulation and aggregation. If you are familiar with HTML, CSS or JavaScript, you can also exploit your talents in Oracle APEX, to create highly customized UI’s.
Oracle APEX is taught at numerous universities and colleges throughout the world, and demand for employees with Oracle APEX experience is at an all time high and continues to grow. Plus, you can get started for free right now.
Business Users
Are you tired of using spreadsheets as a multi-user database? For multi-user purposes, they can be insecure, inefficient and inaccurate (who has the latest email attachment?). Oracle APEX has something for you. In minutes, you can easily create beautiful, responsive applications from the data in a spreadsheet. Choose your favorite enterprise authentication method or use Social authentication and away you go!
Oracle APEX includes powerful self-service reporting features. You can easily add custom filters, sort, aggregate, pivot and chart your data, and even create reports which get emailed to you on a periodic basis.
Architects and CIOs
Do you have application needs which aren’t being met? Are your information assets scattered throughout your organization, using tools that you can’t support or aren’t even aware of? Using Oracle APEX, you can provide an industrial strength «application development service» which can be used to consolidate all of these rogue applications throughout your enterprise. It’s already included with your Oracle database, so there is no additional cost. You can consolidate these applications on the enterprise-ready Oracle database. The information assets can be audited, secured, monitored and shared.
Using Oracle APEX, you can expand the pool of people who are capable of building applications for the department and the enterprise. Oracle APEX has a much lower barrier to entry for creating responsive and powerful business applications.
In an enterprise setting, Oracle APEX provides a scalable and proven platform for applications which can scale across the enterprise. Oracle APEX includes native functionality to integrate with REST and SOAP Services in your organization and in the cloud. Oracle APEX also provides a graphical UI to create and host secure REST services against data and business logic in the database.
Start solving the problems in your organization which are going unsolved today!
Getting Started
Get APEX
Get an Always Free APEX Service
The Oracle APEX Application Development service provides a preconfigured, fully managed, and secured environment in Oracle Cloud to build and deploy world-class applications.
After signing up for your Free Tier account, you can easily create an APEX Service that is free for an unlimited time or spend your free cloud credits on a full, scalable APEX Service.
Or, request a free APEX workspace here
Quickly evaluate Oracle APEX by requesting a free workspace hosted on apex.oracle.com. It takes just a few moments to sign up and within minutes you’ll have your workspace ready to start building your first app.
Watch this short video to see how simple it is to sign up and get started!
Or, download and install Oracle APEX locally
You can download and install Oracle APEX into any edition of Oracle Database. Follow the Oracle APEX Installation Guide for instructions.
Additionally, the free Oracle Database Express Edition (XE) can be used to run APEX locally! Follow these instructions to get the latest APEX release installed on Oracle XE.
Additional Options
Oracle APEX runs anywhere that Oracle Database runs, whether it is on-premises, Oracle Cloud, or anywhere else. Here are some additional ways you can get started.
Use Oracle APEX on Autonomous Database
Oracle Autonomous Database (ADB) in Oracle Cloud comes with APEX ready to go. You can use APEX on any of the ADB workload types. Because the underlying database is autonomous, developers are freed from many management tasks. An Always Free version of ADB provides everything available in Always Free APEX Service, plus the ability to connect SQL clients and non-APEX apps to your database via Oracle Net Services (SQL*Net).
Install on other Oracle Cloud services
It’s easy to download and install APEX into other Oracle Cloud services including Database Cloud Service and Exadata Cloud Service. You can even install into an Oracle Cloud VM. Terraform scripts automate the installation, or you can follow the steps described in Oracle APEX Installation Guide.
Download and run a preconfigured VM
Run APEX in a preconfigured Oracle VM VirtualBox using Database Application Development Virtual Appliance. A single download gives developers a free VM with Oracle Database, Oracle REST Data Services, and APEX ready to run.
Get Data
Now that you have an environment ready, let’s get some data into our workspace that you can use to build your first application.
You can begin with an existing data model or create a new one from scratch. You can use SQL Workshop, which allows you to design or import data models from your browser or use the built-in Quick SQL feature to author a data model using a simple shorthand syntax.
Upload From a File
You can start with a spreadsheet, XML, or JSON and upload it as the basis for your data model.
Use Quick SQL
Use Quick SQL to rapidly create data models using nothing more than shorthand syntax.
Use Sample Datasets
Use the provided sample datasets in SQL Workshop or those available as part of the Create App from Spreadsheet wizard.
The SQL Workshop in Oracle APEX provides a wealth of functionality for managing your data using SQL. SQL Workshop is designed to allow application developers to review and maintain all of the database objects within their associated schemas.
Develop Application
Now that you have data available in your workspace, you can use the Create App wizard to create your first application. Once you’ve created your app, use Page Designer to further enhance your application pages. From Page Designer, you can quickly run your page to see your changes immediately in a new browser tab. From the runtime tab, use the Developer Toolbar to jump back into development. Watch one of these short videos on building your first app.
Creating an Application on Existing Tables
Learn how to build an application based on tables that already exist within your database.
Creating an Application From a Spreadsheet
Learn how to build an application based on data from a spreadsheet.
Oracle APEX 19.1 Video Series
Watch short videos that demonstrate key areas of Oracle APEX.
The App Builder in Oracle APEX provides all of the functionality to develop your apps, including adding pages, managing shared components, and using Page Designer.
Deploy Application
For simple projects, deploying your app can be as easy as sharing the runtime URL and granting end user access.
For systems that separate development and production environments, you can export and import your application in a single file.
Next Steps
Now that you have a workspace and some basic experience with Oracle APEX, try your hand at completing these Hands on Labs to gain even more knowledge and experience building apps.
Platform
Oracle APEX provides you with all the tools you need to build apps in a single, extensible platform, which runs as a part of Oracle Database. Discover the benefits Oracle APEX has to offer and how you can start building superior apps today.
Why Oracle APEX
We could say that we’ve been cloud since day one, or that we were low-code before it was cool. We could even say that we’ve been around for over 20+ years, and that you can still run apps built that long ago, today. Explore how APEX helps you eliminate complexity, deliver results faster, and at a lower-cost. See how low code with APEX compares to alternative approaches to app dev, and learn why choosing APEX makes sense for your next development project.
Low Code
It isn’t just a buzz word. What we used to call declarative programming has been widely adopted by the industry as low code development. Learn how APEX checks all the boxes and resonates with developers as the low code platform of choice. See how you can use APEX to focus on the problem at hand, not on repetitive coding.
Features
We know what components you need to build exceptional experiences. It’s why we have over 18 years of proven success across a multitude of facets, be it data, user interface, security, accessibility, monitoring, or globalizing. We’ve already done the hard work so you can enjoy the fruits of our labor. Learn about all of the features and functionality you get out of the box.
Architecture
Oracle APEX uses a simple architecture that provides zero latency data access, top performance, and scalability, out of the box. Learn more about this architecture, how Oracle APEX uses Oracle REST Data Services, and how the Oracle APEX engine renders pages and has zero-latency access to your data.
Deployment
Your app is your business. That’s why you can choose any deployment strategy that works best for you. While we were cloud from day one, it doesn’t mean that we’re cloud-only. You can run Oracle APEX across the spectrum of Oracle Database Cloud Services, on your own private cloud or 3rd party cloud, on premises, or even in a VM on your laptop. Wherever Oracle Database runs, so does Oracle APEX.
Autonomous Database
Oracle Autonomous Database and Oracle APEX deliver an unparalleled combination of superior data management and proven low-code application development.
Powered by Oracle
Oracle APEX is a fully supported no-cost feature of Oracle Database. This means that if you have Oracle Database, you already have Oracle APEX! This also means that you have native access to all of the Oracle Database capabilities. Learn what it means to be powered by Oracle and explore all of the features and benefits available to you.