Thursday, May 12, 2022

Insights from the SSRS database

SQL Server Reporting Services is a convenient application for generating reports quickly and efficiently. Its back-end components are a bit more confusing to an unsuspecting administrator.

This article delves into the ReportServer database, revealing the tables and data that are used to power SSRS. In addition, the ability to alter data in these tables is presented as a way to avoid time-consuming migration or data modification processes.

Overview of SSRS Metadata

By default, the SSRS database is given the name ReportServer. This can be adjusted when the SSRS instance is installed or at a later time via the Report Server Configuration Manager. Within this database are a set of tables that describe every object in Reporting Services. The following is a brief overview of these tables and the data that resides in each.

A Warning About the ReportServer Database

Microsoft does not formally document the ReportServer database. It is an internal database to Reporting Services but is maintained in plain sight for administrators to use if needed. It can be freely read or written, and no internal process will stop us from doing so.

Because it is undocumented, take extra caution when making any changes to it! Always include this database in routine database backup processes and ensure it is backed up frequently enough to allow for meaningful recovery if it is ever needed. In addition, always perform a backup of this database prior to modifying any data stored within it. Forgetting a WHERE clause or accidentally deleting the wrong rows could result in reports becoming unavailable to end users, so always exercise caution and due diligence before making any changes to ReportServer data!

Catalog

This table contains all of the report objects that a user can interact with via the Web Portal UI, such as reports, data sources, and images. This data is stored as a hierarchy with a root/parent path and all other objects below it in a tree. The following query returns some basic data from this table:

SELECT
        CHILD_ITEM.Path AS Item_Path,
        CHILD_ITEM.Name AS Item_Name,
        CASE
                WHEN CHILD_ITEM.Type = 1 THEN 'Folder (1)'
                WHEN CHILD_ITEM.Type = 2 THEN 'Report (2)'
                WHEN CHILD_ITEM.Type = 3 THEN 'File (3)'
                WHEN CHILD_ITEM.Type = 4 THEN 'Linked Report (4)'
                WHEN CHILD_ITEM.Type = 5 THEN 'Data Source (5)'
                WHEN CHILD_ITEM.Type = 6 THEN 'Report Model (6)'
                WHEN CHILD_ITEM.Type = 7 THEN 'Report Part (7)'
                WHEN CHILD_ITEM.Type = 8 THEN 'Shared Data Set (8)'
                WHEN CHILD_ITEM.Type = 9 THEN 'Report Part (9)'
                WHEN CHILD_ITEM.Type = 11 THEN 'KPI (11)'
                WHEN CHILD_ITEM.Type = 12 THEN 
                        'Mobile Report Folder (12)'
                WHEN CHILD_ITEM.Type = 13 THEN 
                        'PowerBI Desktop Document (13)'
        END AS Item_Type,
        PARENT_ITEM.name AS Parent_Item_Name,
        CHILD_ITEM.Description AS Item_Description,
        CHILD_ITEM.Hidden AS Is_Hidden,
        CHILD_ITEM.CreationDate,
        CHILD_ITEM.ModifiedDate,
        CHILD_ITEM.ContentSize
FROM dbo.Catalog CHILD_ITEM
LEFT JOIN dbo.Catalog PARENT_ITEM
ON PARENT_ITEM.ItemID = CHILD_ITEM.ParentID;

Only a small subset of available columns are returned, but they provide a solid overview of what is contained in the table and how it is formatted:

The results show part of the contents of my local SSRS test server, which includes some folders, reports, and data sources. In general, if detail on reports is needed, this is a good place to start. It can be difficult to get a complete view of the SSRS landscape from the hierarchical web interface, but here it is easy to get a list of objects and then filter accordingly.

Users

Within the site settings in SSRS, users/groups can be added, removed, or have their permissions adjusted. This security is separate from the logins and users that are maintained separately by SQL Server. Some high-level details about all users/groups defined in SSRS can be found in the Users table:

SELECT
        Users.UserID,
        Users.UserName,
        Users.UserType,
        Users.AuthType,
        Users.ModifiedDate
FROM dbo.Users;

The results are as follows:

UserType indicates the source of the user, which typically will be 0 (a SQL Server user/login) or 1 (a domain user or group). AuthType indicates the type of authentication used for the user, which will often be 0/1 (Windows user/group) or 2 (SQL auth). See the references at the end of this article to get full lookups for these user properties.

Subscriptions

This table contains all subscriptions defined in SSRS. Some joins are needed to get info on the report that the subscription is attached to, who owns it, or who modified it last:

SELECT
        Subscriptions.Description,
        Subscriptions.LastStatus,
        Subscriptions.EventType,
        Subscriptions.LastRunTime,
        Subscriptions.Parameters,
        SUBSCRIPTION_OWNER.UserName AS SubscriptionOwner,
        Catalog.Name AS ReportName,
        MODIFIED_BY.UserName AS LastModifiedBy,
        Subscriptions.ModifiedDate
FROM dbo.Subscriptions
INNER JOIN dbo.Users SUBSCRIPTION_OWNER
ON SUBSCRIPTION_OWNER.UserID = Subscriptions.OwnerID
INNER JOIN dbo.Catalog
ON Catalog.ItemID = Subscriptions.Report_OID
INNER JOIN dbo.Users MODIFIED_BY
ON MODIFIED_BY.UserID = Subscriptions.ModifiedByID;

This is some exceptionally useful information! There is no central way to manage subscriptions in SSRS, and therefore, getting a complete view in one place is quite helpful. The results for a few test subscriptions I have created are as follows:

A busy SSRS server could have dozens or even hundreds of subscriptions. A common use of this data is for security audits. Knowing who has access to a report can be exceptionally valuable as the login that accesses data may not be the same as the person that reviews the report. Therefore, a simple audit of SQL Server access may not provide a complete enough picture of who can access a given data set. Subscriptions can be automatically sent to email addresses or files, thereby allowing data to be made available under other security contexts that the SQL auth or domain login a user typically uses.

A SQL Server Agent is created with every subscription to that is used to trigger the report to run at the specified time. The job names, though, are at first glance meaningless:

Typically, when I name a job, I provide something a bit more descriptive than that 😊 These guids that are represented internally in SSRS as the ID of the report schedule. This data can be viewed by adding an additional join onto the previous query, like this:

SELECT
        ReportSchedule.ScheduleID AS AgentJobName,
        Subscriptions.Description,
        Subscriptions.LastStatus,
        Subscriptions.EventType,
        Subscriptions.LastRunTime,
        Subscriptions.Parameters,
        REPLACE(SUBSCRIPTION_OWNER.UserName, 'Datto', 'PIKACHU') 
                  AS SubscriptionOwner,
        Catalog.Name AS ReportName,
        REPLACE(MODIFIED_BY.UserName, 'Datto', 'PIKACHU') AS LastModifiedBy,
        Subscriptions.ModifiedDate
FROM dbo.Subscriptions
INNER JOIN dbo.Users SUBSCRIPTION_OWNER
ON SUBSCRIPTION_OWNER.UserID = Subscriptions.OwnerID
INNER JOIN dbo.Catalog
ON Catalog.ItemID = Subscriptions.Report_OID
INNER JOIN dbo.Users MODIFIED_BY
ON MODIFIED_BY.UserID = Subscriptions.ModifiedByID
INNER JOIN dbo.ReportSchedule
ON ReportSchedule.SubscriptionID = Subscriptions.SubscriptionID
AND ReportSchedule.ReportID = Catalog.ItemID;
The results show the added column of AgentJobName (aka: ScheduleID):

This allows us to see which SQL Server Agent job corresponds to each report subscription. In a pinch, a job could be disabled, executed manually, or adjusted as needed. Note that when a subscription is modified, the job is recreated. Therefore, making extensive changes to these SQL Server Agent jobs is not a good permanent solution. This helps to demystify what the poorly named jobs correspond to, and which subscriptions and reports correspond to which jobs.

Execution logs

There is a central execution log table called ExecutionLogStorage, as well as three preconfigured views that provide some additional details as to what various encoded column values mean. This data is quite valuable as it can be used to audit report executions, successes, and failures. The latter is especially useful as it allows for a customized response to scenarios when reports fail to execute. Responses could vary from automatically rerunning a subscription or emailing an operator with the details of the failure.

The view ExecutionLog cleans up a bit of the execution log data but mostly keeps it in a somewhat cryptic and challenging to read format. The following results are for a straight SELECT * from the view:

The most important columns require no modifications: Start and end times, byte count, row count, and the time spent processing and rendering can assist in troubleshooting reports that are failing or taking a long time to complete. Like any reporting or analytics application, if SSRS gets stuck trying to render a billion rows or a terabyte of data directly to a web browser or file, it’s unlikely to end well. The parameter details are also valuable when trying to reproduce a problem, as well as determine the best solution.

Microsoft later added two more creatively named execution logs: ExecutionLog2 and ExecutionLog3. These provide more detail as well as lookups for some of the available dimensions. The following is a sample of the output from selecting all columns from dbo.ExecutionLog2:

There are more columns that didn’t fit on the screen, including the Source (was the report run live or via a subscription), the status (was it successful?), and a variable XML field with additional info that does not fit into any of the preconstructed columns. This view is a worthwhile expansion on the original execution log. ExecutionLog3 is similar to ExecutionLog2, with only a few tweaks to column names and contents.

A common use of this data is to automatically report on report failures. By default, Reporting Services has no mechanism to let you know when a report fails. Report failures can be indicative of anything from a query error to a timeout to a network outage. Therefore, having reliable reporting on them can improve troubleshooting production issues (on top of allowing us to fix broken reports faster). The following query will return a data set containing any reports that failed in the past hour:

SELECT *
FROM ReportServer.dbo.ExecutionLog2
WHERE DATEDIFF(MINUTE, TimeStart, GETDATE()) <= 60
AND Status <> 'rsSuccess'
AND ReportPath <> ''
AND status <> 'rsHttpRuntimeClientDisconnectionError'
ORDER BY TimeStart ASC;

The filters here are quite useful, as they:

  1. Return reports from the past 60 minutes. Data in ReportServer is stored in the local server time zone, therefore GETDATE() or an equivalent should be used to interrogate this data.
  2. Only return reports that are unsuccessful.
  3. Exclude reports that are run directly from Report Builder (these will have a blank path).
  4. The additional status filter removes reports that failed because the user’s web browser closed.

Here is a sample of some of the results:

A simple SQL Server Agent job or some other scheduled task could run this query hourly and send an alert/report out when any rows are returned. For those looking to minimize work needed on alerting, an SSRS (or some other type of) report could be created that conditionally emails the details based on the contents of this result set.

An important key here is that SQL Server does NOT automatically report on SSRS failures, whether ad-hoc or scheduled via subscriptions. The details of failures are logged, but it is up to the report server owner or another administrator to manage this data and alert appropriately on failures. This provides a head-start on troubleshooting and is far more comfortable than getting the uncomfortable question from somebody important: “Where is my report?”.

Permissions

Reporting Services manages granular permissions for each object in the catalog, such as reports, folders, or data sources. For a large report server, this can be an exceptionally long list of who has access to what – and which specific permissions are granted. The predefined roles have specific actions that are granted by each. The details of these roles are beyond the scope of this article, but a link to Microsoft’s documentation on them is provided after the conclusion as a reference.

The following query provides a complete list of all permissions assigned to any user for any object in SSRS:

SELECT
        CASE
                WHEN catalog.Type = 1 THEN 'Folder (1)'
                WHEN catalog.Type = 2 THEN 'Report (2)'
                WHEN catalog.Type = 3 THEN 'File (3)'
                WHEN catalog.Type = 4 THEN 'Linked Report (4)'
                WHEN catalog.Type = 5 THEN 'Data Source (5)'
                WHEN catalog.Type = 6 THEN 'Report Model (6)'
                WHEN catalog.Type = 7 THEN 'Report Part (7)'
                WHEN catalog.Type = 8 THEN 'Shared Data Set (8)'
                WHEN catalog.Type = 9 THEN 'Report Part (9)'
                WHEN catalog.Type = 11 THEN 'KPI (11)'
                WHEN catalog.Type = 12 THEN 'Mobile Report Folder (12)'
                WHEN catalog.Type = 13 THEN 'PowerBI Desktop Document (13)'
        END AS Item_Type,
        catalog.Path,
        catalog.Name,
        users.UserName,
        roles.RoleName,
        roles.Description
FROM ReportServer.dbo.users
INNER JOIN ReportServer.dbo.policyuserrole
ON users.userid = policyuserrole.userid
INNER JOIN ReportServer.dbo.roles
ON roles.roleid = policyuserrole.roleid
INNER JOIN ReportServer.dbo.catalog
ON catalog.policyid = policyuserrole.policyid
ORDER BY catalog.type, catalog.name, users.username;

The results show an extensive list of who has access to what:

If this list is too long, then it can be pared down to specific objects, users, or types of objects. The table dbo.Roles contains all possible roles that may be assigned to a user in SSRS. The table dbo.Users contains a row per user, which will include some internal users, as well as any added by an administrator. dbo.policyuserrole links users to permissions and catalog items

And more!

There are more tables available in the ReportServer database that can be interrogated to learn about how SSRS is configured and used. For example, favorites are stored in dbo.Favorites and provide a simple linking table between catalog items and users. The following query returns a basic list with this information:

SELECT
        Catalog.Path,
        Catalog.Name,
        Users.UserName
FROM dbo.Favorites
INNER JOIN dbo.Users
ON Users.UserID = Favorites.UserID
INNER JOIN dbo.Catalog
ON Catalog.ItemID = Favorites.ItemID;

The results (all of one row) are as follows:

While it could be interesting to explore every table in the ReportServer database, there is more value here in discussing how and why SSRS data could be changed.

Modifying ReportServer Data

Before discussing how to make changes to ReportServer data, I will iterate again the critical warning from earlier: This is undocumented and not supported by Microsoft. Please back up the ReportServer database before making any changes and be sure to thoroughly QA any changes to ensure they had the intended effect.

With that stark warning out of the way, the first question to answer is: “Why would we even want to do this?” The simplest answer is that SSRS provides no UI for mass-editing entities. If an employee leaves the organization or if there are any significant changes to reporting structures, having to manually update tens, hundreds, or even thousands of entries via the SSRS UI is a recipe for insanity. While a report or subscription that belongs to a disabled user does not afford that user any special access (as they are disabled), most organizations do not want to leave terminated employee accounts associated with anything, as a matter of course.

The primary reason why anyone would issue an UPDATE, INSERT, or DELETE operation against any table in the ReportServer database is to avoid the need to spend hours clicking within the confines of the SSRS web portal. Consider the simple scenario of an administrator leaving an organization. They were configured as the owner on some reports. Without knowing up-front which reports they owned, there is both a challenge of identifying them and then updating them. The following steps can be taken to identify these subscriptions and then update them:

Identify the user in question:

SELECT
        *
FROM dbo.Users
WHERE UserName = 'PIKACHU\epollack';

The results return a single row that identifies a user:

With the user in question identified, subscriptions can be searched specifically for that user as the owner:

SELECT
        *
FROM dbo.Subscriptions
INNER JOIN dbo.Catalog
ON Catalog.ItemID = Subscriptions.Report_OID
AND Catalog.Type = 2
INNER JOIN dbo.Users
ON Subscriptions.OwnerID = Users.UserID
WHERE Subscriptions.OwnerID = '70B6C1EE-89EF-46B1-ABD5-7AA345CAB4BC';

This returns two rows. From here, if they appear valid, they can then be updated like this:

UPDATE Subscriptions
        SET OwnerID = 'F20FC133-9E68-4A6E-938A-B891E8C5020D'
FROM dbo.Subscriptions
INNER JOIN dbo.Catalog
ON Catalog.ItemID = Subscriptions.Report_OID
AND Catalog.Type = 2
INNER JOIN dbo.Users
ON Subscriptions.OwnerID = Users.UserID
WHERE Subscriptions.OwnerID = '70B6C1EE-89EF-46B1-ABD5-7AA345CAB4BC';

Subqueries could be used to reduce the number of queries needed to locate the correct OwnerID values, but the basic principle remains the same. Unlike the system tables in most places in SQL Server, these can be freely modified with few restrictions. While it is possible to enter the wrong value for a column, foreign keys do provide quite a bit of relational integrity within this database. Most tables are keyed to parent tables and would prevent an administrator from entering nonsense values for columns that contain IDs, such as UserID, ItemID, or RoleID.

Similarly, if there were a set of old reports that are no longer needed, it is possible to delete them via the UI, but this would become cumbersome if there were a large number of reports. An easier solution is to delete them via a query:

DELETE Catalog
FROM dbo.Catalog
WHERE Catalog.Path LIKE '/Dev and QA%';

This would delete any catalog items with a specific root path. Executing this DELETE statement results in a foreign key violation as a favorite exists for one of the reports. Therefore, it is necessary to delete the favorites first:

DELETE Favorites
FROM dbo.Catalog
INNER JOIN dbo.Favorites
ON Favorites.ItemID = Catalog.ItemID
WHERE Catalog.Path LIKE '/Dev and QA%';

Once complete, the remaining catalog items can be deleted. Note that in a different database with different report data, there may be more dependencies to deal with before a report, folder, or data source can be deleted. Generally speaking, deleting data directly from the ReportServer database is most efficient when done en masse. It is unlikely to save time if there is only one report to remove. For that scenario, deleting it via the UI is simpler and would likely be faster.

Some other common examples of scenarios when modifying data in the ReportServer database can be a big time-saver:

  • A manager has left the organization, and their subscriptions should be redirected to a new user.
  • Report builder permissions need to be revoked for a large set of reports for a set of users.
  • Report descriptions on all reports need to be appended with some security-related statements.
  • The execution log is quite large and requires regular archival to prevent it from becoming too bloated.

Many other use-cases exist, but these highlight a handful of reasons that an administrator may wish to directly modify data within the ReportServer database.

Insights from the SSRS Database

The entirety of a SQL Server Reporting Services server is encapsulated within the ReportServer database. It can be freely queried, alerted on, and metrics crunched on how SSRS is being used. Tables within this database can also be modified when organizational needs arise that would otherwise be time-consuming or error-prone to do manually.

While the contents of this database are mostly not documented by Microsoft, we can (with a healthy dose of caution) use it to improve SSRS processes by reporting on failed reports, mass-applying security policies, making changes to commonly modified fields, or otherwise preventing the need to perform time-consuming tasks regularly by hand.

This article should serve as a diving board for learning more about how SQL Server Reporting Services operates, and then, using that expanded knowledge, to improve the maintainability of data sources, reports, users, and other commonly referenced entities within SSRS.

References

The following are some references that may assist in researching and using data in the ReportServer database:

Enumerations for the UserType and LoginType within the Users table:
UserType Enum (Microsoft.SqlServer.Management.Smo) | Microsoft Docs

LoginType Enum (Microsoft.SqlServer.Management.Smo) | Microsoft Docs

Details about predefined roles in SSRS:
Role definitions – predefined roles – SQL Server Reporting Services (SSRS) | Microsoft Docs

 

The post Insights from the SSRS database appeared first on Simple Talk.



from Simple Talk https://ift.tt/75sZOht
via

Wednesday, May 11, 2022

Introduction to artificial intelligence

Artificial intelligence (AI) is the ability of machines to replicate or enhance human intellect, such as reasoning and learning from experience. Artificial intelligence has been used in computer programs for years, but it is now applied to many other products and services. For example, some digital cameras can determine what objects are present in an image using artificial intelligence software. In addition, experts predict many more innovative uses for artificial intelligence in the future, including smart electric grids.

AI uses techniques from probability theory, economics, and algorithm design to solve practical problems. In addition, the AI field draws upon computer science, mathematics, psychology, and linguistics. Computer science provides tools for designing and building algorithms, while mathematics offers tools for modeling and solving the resulting optimization problems.

Although the concept of AI has been around since the 19th century, when Alan Turing first proposed an “imitation game” to assess machine intelligence, it only became feasible to achieve in recent decades due to the increased availability of computing power and data to train AI systems.

To understand the idea behind AI, you should think about what distinguishes human intelligence from that of other creatures – our ability to learn from experiences and apply these lessons to new situations. We can do this because of our advanced brainpower; we have more neurons than any animal species.

Today’s computers don’t match the human biological neural network – not even close. But they have one significant advantage over us: their ability to analyze vast amounts of data and experiences much faster than humans could ever hope.

AI lets you focus on the most critical tasks and make better decisions based on acquired data related to a use case. It can be used for complex tasks, such as predicting maintenance requirements, detecting credit card fraud, and finding the best route for a delivery truck. In other words, AI can automate many business processes leaving you to concentrate on your core business.

Research in the field is concerned with producing machines to automate tasks requiring intelligent behavior. Examples include control, planning and scheduling, the ability to answer diagnostic and consumer questions, handwriting, natural language processing and perception, speech recognition, and the ability to move and manipulate objects.

History of AI and how it has progressed over the years

With so much attention on modern artificial intelligence, it is easy to forget that the field is not brand new. AI has had a number of different periods, distinguished by whether the focus was on proving logical theorems or trying to mimic human thought via neurology.

Artificial intelligence dates back to the late 1940s when computer pioneers like Alan Turing and John von Neumann first started examining how machines could “think.” However, a significant milestone in AI occurred in 1956 when researchers proved that a machine could solve any problem if it were allowed to use an unlimited amount of memory. The result was a program called the General Problem Solver (GPS).

Over the next two decades, research efforts focused on applying artificial intelligence to real-world problems. This development led to expert systems, which allow machines to learn from experience and make predictions based on gathered data. Expert systems aren’t as complex as human brains, but they can be trained to identify patterns and make decisions based on that data. They’re commonly used in medicine and manufacturing today.

A second major milestone came in 1965 with the development of programs like Shakey the robot and ELIZA, which automated simple conversations between humans and machines. These early programs paved the way for more advanced speech recognition technology, eventually leading to Siri and Alexa.

The initial surge of excitement around artificial intelligence lasted about ten years. It led to significant advances in programming language design, theorem proving, and robotics. But it also provoked a backlash against over-hyped claims that had been made for the field, and funding was cut back sharply around 1974.

After a decade without much progress, interest revived in the late 1980s. This revival was primarily driven by reports that machines were becoming better than humans at “narrow” tasks like playing checkers or chess and advances in computer vision and speech recognition. This time, the emphasis was on building systems that could understand and learn from real-world data with less human intervention.

These developments continued slowly until 1992, when interest began to increase again. First, technological advances in computing power and information storage helped boost interest in research on artificial intelligence. Then, in the mid-1990s, another major boom was driven by considerable advances in computer hardware that had taken place since the early 1980s. The result has been dramatic improvements in performance on several significant benchmark problems, such as image recognition, where machines are now almost as good as humans at some tasks.

The early years of the 21st century were a period of significant progress in artificial intelligence. The first major advance was the development of the self-learning neural network. By 2001, its performance had already surpassed human beings in many specific areas, such as object classification and machine translation. Over the next few years, researchers improved its performance across a range of tasks, thanks to improvements in the underlying technologies.

The second significant advancement in this period was the development of generative model-based reinforcement learning algorithms. Generative models can generate novel examples from a given class, which helps learn complex behaviors from very little data. For example, they can be used to learn how to control a car from only 20 minutes of driving experience.

In addition to these two advances, there have been several other significant developments in AI over the past decade. There has been an increasing emphasis on using deep neural networks for computer vision tasks, such as object recognition and scene understanding. There has also been an increased focus on using machine learning tools for natural language processing tasks such as information extraction and question answering. Finally, there has been a growing interest in using these same tools for speech recognition tasks like automatic speech recognition (ASR) and speaker identification (SID).

Different fields under AI to clear common misconceptions

Artificial Intelligence is the most trending field of computer science. However, with all the new technology and research, it’s growing so fast that it can be confusing to understand what is what. Furthermore, there are many different fields within AI, each one having its specific algorithms. Therefore, it’s essential to know that AI is not a single field but a combination of various fields.

Artificial Intelligence (AI) is the general term for being able to make computers do things that require intelligence if done by humans. AI can be broken down into two major fields, Machine Learning (ML) and Neural Networks (NN). Both are subfields under Artificial Intelligence, and each one has its methods and algorithms to help solve problems.

An image showing 3 circles. Deep Learning is the innermost circle. Outside of that is Machine Learning., and the largest circle encompassing the others is Artificial Intelligence t

Machine learning

Machine Learning (ML) makes computers learn from data and experience to improve their performance on some tasks or decision-making processes. ML uses statistics and probability theory for this purpose. Machine learning uses algorithms to parse data, learn from it, and make determinations without explicit programming. Machine learning algorithms are often categorized as supervised or unsupervised. Supervised algorithms can apply what has been learned in the past to new data sets; unsupervised algorithms can draw inferences from datasets. Machine learning algorithms are designed to strive to establish linear and non-linear relationships in a given set of data. This feat is achieved by statistical methods used to train the algorithm to classify or predict from a dataset.

Deep learning

Deep learning is a subset of machine learning that uses multi-layered artificial neural networks to deliver state-of-the-art accuracy in object detection, speech recognition and language translation. Deep learning is a crucial technology behind driverless cars and enables the machine analysis of large amounts of complex data — for example, recognizing the faces of people who appear in an image or video.

Neural networks

Neural networks are inspired by biological neurons in the human brain and are composed of layers of connected nodes called “neurons” that contain mathematical functions to process incoming data and predict an output value. Artificial neural network learns by example, similarly to how humans learn from our parents, teachers, and peers. They consist of at least three layers: an input layer, hidden layers, and an output layer. Each layer contains nodes (also known as neurons) which have weighted inputs that compute the output.

A image showing a graph. Y axis is performance, X axis is the amount of data. The Deep Learning curve continues to go up with more data which Traditional machine learning plateaus.

The performance of traditional machine learning models plateau and throwing any more data doesn’t help improve the performance. Deep learning models continue to improve in performance with more data.

These fields have different algorithms, depending on the use case. For example, we have decision trees, random forests, boosting, support vector machines (SVM), k-nearest neighbors (kNN), and others for machine learning. For neural networks, we have convolutional neural networks (CNNs), recurrent neural networks (RNNs), long short-term memory networks (LSTMs), and more.

However, classifying AI according to its strength and capabilities would mean further subdividing it into “narrow AI” and “general AI.” Narrow AI is about getting machines to do one task really well, like image recognition or playing chess. General AI means devices that can do everything humans can do and more. Today’s research focuses on narrow AI, but many researchers would like machine learning to eventually achieve general AI.

How AI stands out in different industries.

AI is a booming technology that the global community has accepted. It has been revolutionizing the industry from various sectors for quite some time. It is a comprehensive technology that is being applied in almost every industry. This section discusses how AI is impacting service delivery in various sectors.

Fully self-driving cars are now a reality. Tesla is the first company to make a car with all of the sensors, cameras, and software needed for a computer to drive itself from start to finish. Trucks may be the next primary target for autonomy: self-driving trucks will enormously impact road safety and infrastructure and save companies money by reducing labor costs.

A few other industries are also implementing AI. For example, in finance, AI helps with forecasting and supports hedge-fund investment decisions. Predictive analytics (or forecasting) applies artificial intelligence using machine learning and statistical techniques to make predictions about future events based on previous data. For example, you can use forecasting to predict product sales, customer demand, or even stock prices. One popular example of predictive analytics is Amazon’s product recommendations engine (also known as “Customers who bought this item also bought”). It uses past purchase data from millions of customers to recommend products based on the users’ preferences.

In healthcare, AI is helping doctors to diagnose diseases by gathering data from health records, scanning reports, and medical images. This helps doctors to make faster diagnoses and guide the patient for further tests or prescribe medications. In addition, AI can be used in the treatment process by monitoring patients and alerting their doctors when something goes wrong. According to Forbes, AI will save over 7 million lives in 2035.

In retail, AI does everything from stock management to customer service chatbots. As a result, many businesses are taking advantage of AI to improve productivity, efficiency, and accuracy. In addition, companies find new ways to use AI to make life easier for their customers and employees, from product design to customer service.

The current state of AI-based software systems.

The recent advancements in AI have led to the emergence of a new type of system called Generative Adversarial Networks (GANs), which generate realistic images, text, or audio. Due to their remarkable capabilities, some people are concerned that this technology could replace humans in the future.

GANs are just one example of how AI is changing our lives. This section explores more current AI examples and its applications in software systems such as GPT3, DALL.E, and virtual reality/augmented reality (VR/AR).

AI-based software systems are comprised of many layers such as foundational models, advanced algorithms, and automated reasoning tools. Some of the most popular AI-based systems that use these layers include GPT3, DALL.E, AlphaGo, RoBERTa, and many others.

DALL.E and GPT3 are large-scale models that have achieved remarkable results in computer vision and natural language processing (NLP).

The GPT3 model is an NLP model based on a deep learning algorithm called transformers. It was trained on a corpus of text from Common Crawl and published in 2020. GPT3 uses a large dataset trained in the English language to produce outputs based on the inputted information. The model can be trained to perform any task imaginable, from generating text to solving math problems. Also, we can use GPT3 to generate text, translate between languages, answer questions about images, and more.

The DALL.E model is an image generator based on a deep learning algorithm called variational autoencoders (VAEs). Similarly, DALL.E can be trained using an image dataset to produce images based on the inputted text descriptions. It was trained on datasets such as ImageNet and published in 2021. We can use DALL.E to generate images that match captions or URLs given by users. These models have been developed by OpenAI, which has close ties to the US government and military-industrial complex (MIC).

DeepMind created AlphaGo as a program that would play the ancient game Go without anyone’s help. The game is similar to chess but much more complex due to its simple rules and many possible moves per turn. AlphaGo used reinforcement learning to learn how to play the game better over time by playing against itself repeatedly until it mastered every possible situation that could occur in a game of Go with 100% accuracy.

RoBERTa is an algorithm from Facebook AI Research (FAIR) that uses deep learning techniques to solve problems in natural language processing (NLP), such as sentence classification or machine translation.

The Future of AI. What to expect from AI in the next few years or decades

Artificial intelligence has come a long way, but it’s about to make a huge leap. Artificial general intelligence (AGI), the kind of AI capable of doing any intellectual task that a human being can do, is still a ways off, but we’re already starting to see plenty of progress in other areas of AI. Here’s what you can expect soon:

Artificial Intelligence will make more jobs obsolete as it takes over more and more tasks

The reason why is simple: if you can replace one person with an AGI system, you don’t need one computer to do the work – you can spread it out across thousands or millions of computers. That’s only possible because a general AI system can learn from past experiences and improve itself, meaning that it doesn’t have to be reprogrammed for every new task. In fact, there’s no reason why an AGI system would need humans at all – once it learns enough, it could design its own machines or find ways to automate entire industries.

The advent of AI is transforming the business landscape and changing people’s lives for the better. In the coming years, most industries will see a significant transformation due to new-age technologies like cloud computing, Internet of Things (IoT), and Big Data Analytics. All these factors profoundly influence how businesses operate today and are also finding applications in other areas like military, healthcare, and infrastructure development.

To build an engaging metaverse that appeals to millions of users who want to learn, create, and inhabit virtual worlds, AI must be used to enable realistic simulations of the real world. People need to feel immersed in the environments they participate in. AI is helping to achieve this reality by making objects look more realistic and enabling computer vision so users can interact with simulated objects using their body movements.

Concerns surrounding the advancement and usage of AI

AI is a very powerful idea, but it’s not magic. The key thing to remember about AI is that it learns from data. The model and algorithm underneath are only as good as the data put into them. This means that data availability, bias, improper labeling, and privacy issues can all significantly impact the performance of an AI model.

Data availability and quality are critical for training an AI system. Some of the biggest concerns surrounding AI today relate to potentially biased datasets that may produce unsatisfactory results or exacerbate gender/racial biases within AI systems. When we research different types of machine learning models, we find that certain models are more susceptible to bias than others. For example, when using deep learning models (e.g., neural networks), the training process can introduce bias into the model if a biased dataset is used during training.

However, other machine learning models (e.g., random forests) can be less sensitive to the bias in the data during training. For example, if a dataset contains information about many different variables but only one variable is used to make decisions (e.g., gender), this model will tend to be more biased toward that variable than random forests that consider all variables equally weighted by default.

Other concerns need to be taken into account with the advancement and usage of AI. These include data availability, computational power, and privacy, such as health data. People’s data is needed to develop models, but how do we get such data given how protected health data needs to be.

As artificial intelligence becomes more common, it’s only natural that there are increasing requirements for processing power. As a result, AI researchers use supercomputers to develop algorithms and models on a massive and complex scale.

This is especially true of deep learning, a type of machine learning that uses algorithms to recognize patterns in large data sets like images or sound. The main issue with DL is that it requires enormous computational power. To train a neural network using DL, you need to feed vast amounts of data into the system — for example, thousands or millions of pictures — and then let it figure out how to tell one from another on its own. This training process is complex and laborious, but it is also computationally expensive. Model development can take days or even weeks on a single high-end GPU or CPU capable of delivering lots of computational power. To make matters worse, once you train the model, you need a supercomputer to execute the model at full capacity. Google’s investments in TPUs (Tensor Processing Units) attempt to solve this problem using state-of-the-art hardware technology.

Another source of concern in the development of AI is how automated systems will ultimately be used. For example, should we consider holding corporations responsible for the actions of intelligent machines they develop? Or should we consider holding machine developers accountable for their work?

Conclusion

Artificial intelligence (AI) is the intelligence of machines and the branch of computer science that aims to create it. AI is today’s dominant technology and will continue to be a significant factor in various industries for years to come. As AI systems become more advanced, they are not only poised to disrupt multiple industries with their impact but also raise concerns about how we should handle such incredible power.

This field has evolved a great deal over the years. It has gone from being a subject of popular science fiction to a significant part of our lives today. By examining AI from its past, it is possible to better understand its present and predict its future, as we have done in this article.

 

The post Introduction to artificial intelligence appeared first on Simple Talk.



from Simple Talk https://ift.tt/Twkd7XJ
via

Buying an SSD card for a grandchild

We recently ordered a tablet for our 8-year-old grandson. We ensured that it would support a decent-sized SSD card, 128 GB, for storing all the photos and videos he will likely take. He’ll mostly play games or watch videos on the tablet, and his favorite video is Dragon’s Doom.

Purchasing this gift made me think about how much has changed over the past 40 years or so. I remember the excitement of buying a 5.25-inch floppy drive and modem for our TI-99/4A back in the early 80s. I caught my first look at BASIC in 1980 on a TRS-80 but figured out how to write a few simple programs on the TI. We wasted spent a lot of time on BBS (The Bulletin Board System) and CompuServe before dial-up internet was available in the 90s. I can still hear that modem connecting!

Our first desktop PC was slow, probably even for that time, as we bought a clearance model. We upgraded it many times during its life and had to use a compression utility to get more drive space. I don’t recall the specs, but the hard drive was probably just a couple of hundred megabytes. These were the 16-bit days, and software arrived with printed books and lots of installation floppies. Around 1995, I purchased a laptop. This was the beginning of always having multiple working computers in the house.

Photography is another example. Taking home photos was once cumbersome and expensive. I had a 126 Kodak Instamatic, and I needed the film cartridge and a sometimes a flashcube to take a photo.  Then, once the film was used up, possibly over several months, it had to be taken in to be developed. Today, most phones are equipped to take digital photos and videos – no film needed.

Speaking of phones, how did we manage to keep track of each other before mobile phones? The chances of catching someone at home at the right time to answer a phone call on a landline seems astronomical, but we did it. A recent science fiction series, Upload, shows the characters using a handphone. There’s no need to carry a phone around as it’s embedded in one’s hand. They also have a 3D instant food printer that prints real meals. I’m not sure which one of these will be available in real life first, but I need that food printer now!

That tiny SSD card that will store my grandson’s photos was unimaginable just a few decades ago. Maybe in 20 years, we will look back at today’s world and wonder how we managed with such primitive technology.

Commentary Competition

Enjoyed the topic? Have a relevant anecdote? Disagree with the author? Leave your two cents on this post in the comments below, and our favourite response will win a $50 Amazon gift card. The competition closes two weeks from the date of publication, and the winner will be announced in the next Simple Talk newsletter.

The post Buying an SSD card for a grandchild appeared first on Simple Talk.



from Simple Talk https://ift.tt/s83o2DU
via

Tuesday, May 10, 2022

How to run Kubernetes clusters locally on Windows

Kubernetes production clusters are typically run on cloud platforms. However, running and deploying Kubernetes applications on cloud platforms such as Google Kubernetes Engine is costly. These high costs can restrict the Kubernetes learning process for beginners. However, running Kubernetes clusters locally helps you efficiently test applications without disrupting the production environment or paying for cloud services. 

To make things easier, the Kubernetes team developed two tools,  Minikube and Kind, that allow Kubernetes users to run clusters locally without spending a dollar. This article will cover how to do it with Kind. Kind is a command-line tool used to run Kubernetes clusters locally on your computer using Docker containers. Kind works with Docker by loading Docker containers into Kind clusters. A Kubernetes cluster is a group of nodes used to run containerized applications.

Kind uses a virtual machine on your pc to create nodes. Kind is also widely used to test and implement continuous integration tasks. Kind runs clusters locally from your computer making it easy to develop your Kubernetes applications without the need for a server.

Kind is good at creating clusters with multiple nodes. The more nodes you have, the more containerized applications you can run. These clusters created by Kind can be operated and interacted with using Kubectl. Kubectl is a command line that enables you to execute commands that communicate with your Kubernetes cluster and make changes.

In this article, you will learn how to install Kind on Windows. In addition, you will learn how to create a cluster using Kind and create a service.

Table of contents

  1. Prerequisites
  2. How to install Kind on Windows
  3. How to create and delete a cluster
  4. How to create a cluster with multiple nodes
  5. How to create a service
  6. How to export cluster logs
  7. Conclusion

Prerequisites

  • A Windows machine that has at least 8GB RAM. Using a machine that has less than 8GB of RAM will raise memory issues and complications when running a Kind cluster.
  • You need to have installed Kubectl before starting this tutorial; if you haven’t installed Kubectl, you install it from here.
  • Kind cannot function without Docker, install Docker from here.
  • In this tutorial, you will install Kind using Chocolatey. Download Chocolatey here.
  • Run Windows PowerShell as an Administrator whenever executing any Kind or Kubectl commands.

How to install Kind on Windows

In this article, you will learn how to download Kubernetes Kind using Chocolatey. Use the following command to download Kind using chocolatey:

choco install kind

Chocolatey will install 6 packages. After Kind has been successfully installed, you will get the list of the installed artifacts:

kb2919355 v1.0.20160915
dotnetfx v4.8.0.20190930
docker-desktop v4.4.4
kb2919442 v1.0.20160915
chocolatey-dotnetfx.extension v1.0.1
kind v0.11.1

To check if Kind has been installed successfully, execute the following command on Powershell:

kind version

If Kind has been installed successfully you will get the version output and your computer’s processor:

kind v0.11.1 go1.16.4 windows/amd64

Now you’re done installing Kind on Windows. You can now start creating clusters locally using kind. If you ever get stuck using Kind, use the command shown below to get all available commands:

kind -h

You will get the following list of commands as output:

Available Commands:
  build       Build one of [node-image]
  completion  Output shell completion code for the specified shell (bash, zsh or fish)
  create      Creates one of [cluster]
  delete      Deletes one of [cluster]
  export      Exports one of [kubeconfig, logs]
  get         Gets one of [clusters, nodes, kubeconfig]
  help        Help about any command
  load        Loads images into nodes
  version     Prints the kind CLI version

Flags:
  -h, --help              help for kind
      --loglevel string   DEPRECATED: see -v instead
  -q, --quiet             silence all stderr output
  -v, --verbosity int32   info log verbosity
      --version           version for kind

Use the -h flag to get more information about any command. For example, executing this command:

kind build -h

gives you the following detailed information about the build command:

Usage:
kind build [flags]
kind build [command]

Available Commands:
node-image Build the node image

Flags:
-h, --help help for build

Global Flags:
--loglevel string DEPRECATED: see -v instead
-q, --quiet silence all stderr output
-v, --verbosity int32 info log verbosity

Use "kind build [command] --help" for more information about a command.

How to create and delete a cluster

Clusters are the holy grail of Kubernetes. Clusters comprise containers with all the runtime resources needed to run applications in different operating systems.

Use the following command to create a default Kind cluster:

kind create cluster

The above command will create a default cluster called kind. If you want to use a specific name, add the --name flag to the kind create cluster command. Here is an example:

kind create cluster --name simple-cluster

The Kind create command has the following arguments and options

  • --quiet: this flag silences all stderr output.
  • --verbosity int32: This flag will log verbosity information.

When your cluster has been created successfully, you will get the following output:

Creating cluster "simple-cluster" ...
• Ensuring node image (kindest/node:v1.21.1) 🖼 ...
✓ Ensuring node image (kindest/node:v1.21.1) 🖼
• Preparing nodes 📦 ...
✓ Preparing nodes 📦
• Writing configuration 📜 ...
✓ Writing configuration 📜
• Starting control-plane 🕹 ...
✓ Starting control-plane 🕹
• Installing CNI 🔌 ...
✓ Installing CNI 🔌
• Installing StorageClass 💾 ...
✓ Installing StorageClass 💾
Set kubectl context to "kind-simple-cluster"

After you have created your cluster, use the following command to check if the cluster has been created successfully or get the list of all Kind clusters running:

kind get clusters

If you want to interact with a specific cluster locally. Use the following command and specify the name of the cluster (kind-<cluster-name>):

kubectl cluster-info --context kind-simple-cluster

You will get the following output which shows you where the Kubernetes control plane and CoreDNS are running at:

Kubernetes control plane is running at https://127.0.0.1:2450
CoreDNS is running at https://127.0.0.1:2450/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy

The cluster’s configuration access will be stored in the ${HOME}/.kube/config file. This file acts as your cluster’s manifest. Here is the configuration access of the default Kind cluster created earlier:

apiVersion: v1
clusters:
- cluster:
    certificate-authority-data:
    server: https://127.0.0.1:2474
  name: kind-kind
contexts:
- context:
    cluster: kind-kind
    user: kind-kind
  name: kind-kind
current-context: kind-kind
kind: Config
preferences: {}
users:
- name: kind-kind
  user:
    client-certificate-data:
    client-key-data:

A corresponding Docker container will be created automatically when creating a Kind cluster. Use the following docker command to see the corresponding docker container:

docker ps

You will get the following information:

CONTAINER ID: 22add82af339
IMAGE: kindest/node:v1.21.1
COMMAND:"/usr/local/bin/entr..."
CREATED: About an hour ago
STATUS: Up About an hour
PORTS: 127.0.0.1:2450->6443/tcp NAMES:simple-cluster-control-plane

To view nodes created by the cluster, use the following command to view them:

kubectl get nodes

You will get the following information:

NAME                         STATUS ROLES               AGE VERSION
simple-cluster-control-plane Ready control-plane,master 89m v1.21.1

Use the following command to delete a cluster:

kind delete cluster

After the cluster has been successfully deleted, you will get the following information:

Deleting cluster "kind" ...

To delete a cluster without the default name, use the –name flag.

How to create a cluster with multiple nodes

A Kubernetes node is a virtual machine that runs a cluster. There are two types of nodes which are:

  • Worker node: A worker node executes and runs applications and containers assigned to it.
  • control-plane: A control-plane controls all the worker nodes.

You’ll need a YAML file that defines the nodes when creating a multi-node cluster.

A node can also be a physical machine. To add more nodes to your cluster, start by creating a cluster and adding different roles of nodes you want to add to your cluster. Save the following in kind-config.yaml.

kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
nodes:
- role: control-plane
- role: worker
- role: worker

After saving the YAML file that has the above contents. Use the following command to apply changes:

kind create cluster --name best-cluster --config kind-config.yaml

You will get the following output; this time the output will show that Kind is creating multiple nodes and show that it is joining worker nodes at the bottom of the output:

Creating cluster "best-cluster" ...
• Ensuring node image (kindest/node:v1.21.1) 🖼 ...
✓ Ensuring node image (kindest/node:v1.21.1) 🖼
• Preparing nodes 📦 📦 📦 ...
✓ Preparing nodes 📦 📦 📦
• Writing configuration 📜 ...
✓ Writing configuration 📜
• Starting control-plane 🕹 ...
✓ Starting control-plane 🕹
• Installing CNI 🔌 ...
✓ Installing CNI 🔌
• Installing StorageClass 💾 ...
✓ Installing StorageClass 💾
• Joining worker nodes 🚜 ...
✓ Joining worker nodes 🚜

Set kubectl context to "kind-best-cluster"

You can now use your cluster with:

kubectl cluster-info --context kind-best-cluster
Thanks for using kind! 😊

To check if the nodes have been created successfully and are ready, execute the following command:

kubectl get nodes

You will get the following output:

NAME                       STATUS   ROLES                AGE   VERSION
best-cluster-control-plane Ready    control-plane,master 4m59s v1.21.1
best-cluster-worker        NotReady <none>               90s   v1.21.1
best-cluster-worker2       NotReady <none>               90s   v1.21.1

How to create a service

A Kubernetes service is used to expose your cluster and connect with authorized traffic outside your cluster. An ingress controller is a type of load balancer service that routes traffic to your service.

The following YAML file creates a pod, service, and the ingress controller objects. The service will receive traffic through the 5678 port. The ingress controller version is set to networking.k8s.io/v1.

Start by creating a YAML file that will define and configure the service. Add the following content to the YAML file:

kind: Pod
apiVersion: v1
metadata:
  name: best-cluster
  labels:
    app: best-cluster
spec:
  containers:
  - name: best-cluster
    image: hashicorp/http-echo:0.2.3
    args:
    - "-You just deployed your first service"
---
kind: Service
apiVersion: v1
metadata:
  name: simple-service
spec:
  selector:
    app: best-cluster
  ports:
  # Default port used by the image
  - port: 5678
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: simple-ingress
spec:
  rules:
  - http:
      paths:
      - pathType: Prefix
        path: "/simple"
        backend:
          service:
            name: simple-service
            port:
              number: 5678
---

After saving your YAML file, use the following command to deploy the service:

kubectl apply -f simple-service.yaml

Execute the following command to check if the service is running:

kubectl get services

You will get the following output:

NAME              TYPE      CLUSTER-IP    EXTERNAL-IP   PORT(S)  AGE
kubernetes        ClusterIP 10.96.0.1     <none>        443/TCP  72m
simple-service    ClusterIP 10.96.245.41  <none>        5678/TCP 56s

The above output shows that your cluster is now ready to receive traffic from outside the cluster through the service you just created.

How to export cluster logs

Kubernetes logs give you visibility on how your cluster performs. Some vulnerabilities and defects will be identified when inspecting and auditing logs. Kind has the following command that is used to export cluster logs to your desired directory on your pc:

kind export logs C:\Users\redgate

The above command will give you the following output, exporting logs of the default cluster. Use the –name flag if you have named the cluster something else:

Exporting logs for cluster “kind” to:
C:\Users\redgate

The structure of the logs will look like this in the folder you exported them to

├── docker-info.txt
└── kind-control-plane/     
         ├── containers     
         ├── docker.log     
         ├── inspect.json     
         ├── journal.log     
         ├── kubelet.log     
         ├── kubernetes-
version.txt
        └── pods/

Conclusion

In this article you have learned:

  1. How to install Kind on Windows.
  2. How to create a cluster using Kind.
  3. How to create a cluster with multiple nodes.
  4. How to create a service.

The above skills are enough to get you started with the journey of creating Kubernetes clusters using Kind. You can advance your Kubernetes skills on the Kubernetes official page here.

 

The post How to run Kubernetes clusters locally on Windows appeared first on Simple Talk.



from Simple Talk https://ift.tt/29nW1CD
via

Monday, May 9, 2022

Working with MySQL stored functions

The series so far:

  1. Getting started with MySQL
  2. Working with MySQL tables
  3. Working with MySQL views
  4. Working with MySQL stored procedures
  5. Working with MySQL stored functions

In the previous three articles in this series, I focused on creating basic database objects that you can use to get started with MySQL. You learned how to build an initial database and then add tables, views, and stored procedures. In this article, I cover one more important type of object, the stored function, a routine that is stored in a database and can be invoked on-demand, similar to a user-defined scalar function in SQL Server or other database systems.

Stored functions work much like MySQL built-in functions. You can call either type of function in an expression, such as those in a query’s SELECT, WHERE, or ORDER BY clause. For example, you might use the CAST built-in function in a SELECT clause to convert a column to a different data type, as in CAST(plane_id AS CHAR). The expression converts the plane_id column (an integer) to a character data type. In the same way, you can use a stored function in your expression, applying your own logic to the plane_id column or any other column.

Before I go any further with stored functions, it’s important to note that there are three different types of MySQL functions that you can add at the database or server level:

  • Stored functions. Functions that you create as database objects by using the CREATE FUNCTION statement.
  • Loadable functions. Functions that are compiled as library files and then loaded to the server dynamically by running a CREATE FUNCTION statement.
  • Native functions. Functions that are added to the server by modifying the MySQL source code and compiling it into mysqld.

This article focuses on creating stored functions, which share many of the same characteristics as MySQL stored procedures. In fact, I had considered writing about both of them in the previous article, but I think there are enough differences between them to warrant a separate article. It also provides a more consistent way of introducing each of the primary MySQL object types, even if it does mean repeating some of the information. With this in mind, let’s get started with the stored function.

Preparing your MySQL environment

As with the previous few articles, the examples in this article are based on the travel database. If you already have it installed, you can skip this section. If not, you can start by running the following SQL script to create the database and its tables:

DROP DATABASE IF EXISTS travel;
CREATE DATABASE travel;
USE travel;
CREATE TABLE manufacturers (
  manufacturer_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  manufacturer VARCHAR(50) NOT NULL,
  create_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  last_update TIMESTAMP NOT NULL 
    DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (manufacturer_id) ) 
ENGINE=InnoDB AUTO_INCREMENT=1001;
CREATE TABLE airplanes (
  plane_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  plane VARCHAR(50) NOT NULL,
  manufacturer_id INT UNSIGNED NOT NULL,
  engine_type VARCHAR(50) NOT NULL,
  engine_count TINYINT NOT NULL,
  max_weight MEDIUMINT UNSIGNED NOT NULL,
  wingspan DECIMAL(5,2) NOT NULL,
  plane_length DECIMAL(5,2) NOT NULL,
  parking_area INT GENERATED ALWAYS AS 
        ((wingspan * plane_length)) STORED,
  icao_code CHAR(4) NOT NULL,
  create_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  last_update TIMESTAMP NOT NULL 
    DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (plane_id),
  CONSTRAINT fk_manufacturer_id FOREIGN KEY (manufacturer_id) 
    REFERENCES manufacturers (manufacturer_id) ) 
ENGINE=InnoDB AUTO_INCREMENT=101;

The airplanes table includes a foreign key that references the manufacturers table, so be sure to create the tables in the order shown here. After you create the tables, you can add sample data to them so you’ll be able to test your function. To populate the tables, run the following INSERT statements:

INSERT INTO manufacturers (manufacturer)
VALUES ('Airbus'), ('Beechcraft'), ('Piper');
INSERT INTO airplanes 
  (plane, manufacturer_id, engine_type, engine_count, 
    max_weight, wingspan, plane_length, icao_code)
VALUES 
  ('A380-800', 1001, 'jet', 4, 1267658, 261.65, 238.62, 'A388'),
  ('A319neo Sharklet', 1001, 'jet', 2, 166449, 117.45, 111.02, 'A319'),
  ('ACJ320neo (Corporate Jet version)', 1001, 'jet', 2, 174165, 
               117.45, 123.27, 'A320'),
  ('A300-200 (A300-C4-200, F4-200)', 1001, 'jet', 2, 363760, 147.08, 
               175.50, 'A30B'),
  ('Beech 390 Premier I, IA, II (Raytheon Premier I)', 1002, 'jet', 
               2, 12500, 44.50, 46.00, 'PRM1'),
  ('Beechjet 400 (from/same as MU-300-10 Diamond II)', 1002, 'jet', 
              2, 15780, 43.50, 48.42, 'BE40'),
  ('1900D', 1002, 'Turboprop', 2,17120,  57.75, 57.67, 'B190'),
  ('PA-24-400 Comanche', 1003, 'piston', 1, 3600, 36.00, 24.79, 'PA24'),
  ('PA-46-600TP Malibu Meridian, M600', 1003, 'Turboprop', 1, 6000, 
         43.17, 29.60, 'P46T'),
  ('J-3 Cub', 1003, 'piston', 1, 1220, 38.00, 22.42, 'J3');

As with the CREATE TABLE statements, you should run the INSERT statements in the order specified here so you don’t violate the foreign key defined on the airplanes table. Once you have the tables set up and populated, you can start creating stored functions.

Creating a stored function in MySQL

To add a stored function to a MySQL database, you can use the CREATE FUNCTION statement. The statement is similar to a CREATE PROCEDURE statement in several respects. In both cases, you must provide a name for the object and you must define a routine. You also have the option to include a DEFINER clause, one or more characteristics, and one or more parameters.

Despite these similarities, the CREATE FUNCTION statement differs in several important ways:

  • A stored function can return only one value, unlike a stored procedure, which can return multiple values or an entire result set.
  • A stored function supports input parameters only. A stored procedure supports IN, OUT, and INOUT parameters in any combination.
  • A stored function must include a RETURNS clause in its definition before the routine. The clause specifies the data type for the function’s returned value. Stored procedures do not support this clause.
  • A stored function’s routine must include a RETURN statement that specifies the function’s returned value. The routine does not have to include any other statements, only the RETURN statement. If it does include other statements, only the RETURN statement can return a value.

With these guidelines in mind, let’s look at a simple example of a CREATE FUNCTION statement, which defines a stored function that converts pounds to kilograms:

DELIMITER //
CREATE FUNCTION lbs_to_kg(lbs MEDIUMINT UNSIGNED)
RETURNS MEDIUMINT UNSIGNED 
DETERMINISTIC
BEGIN
  RETURN (lbs * 0.45359237);
END//
DELIMITER ;

The function is named lbs_to_kg and includes one input parameter named lbs. You do not have to include a parameter when defining a function, but typically you’ll want at least one. If you add more than one, you need to separate them with commas.

The parameter definition is enclosed in parentheses and includes the parameter’s data type, MEDIUMINT UNSIGNED. I chose this data type because I ultimately want to use the function for the max_weight column in the airplanes table, which is also defined with that data type.

In addition, I used the MEDIUMINT UNSIGNED data type for the RETURNS clause. The clause specifies that the function’s returned value should be an integer in the range permitted by this data type. I figured we were safe with this data type because one pound is equivalent to 0.45359237 kilograms, so the returned value would never exceed the maximum value in the max_weight column.

If you want to support a greater range of values, you can instead use the INT or BIGINT data type for the lbs parameter and the RETURNS clause. This would provide you with more flexibility should you want to use the function to convert values that exceed those in the max_weight column.

The RETURNS clause is followed by the DETERMINISTIC characteristic. A characteristic is one of several options that can be added to a function definition, each one affecting the function in a different way. For example, you can add a characteristic to indicate the routine language or to define the routine’s nature. These are the same characteristics available to stored procedures.

The DETERMINISTIC characteristic indicates that the function will return the same results for the same input parameter each time the function runs. By default, a function is considered nondeterministic unless specified otherwise. Using the DETERMINISTIC characteristic can help the optimizer make better execution plan choices. However, assigning the characteristic to a nondeterministic function could cause the optimizer to make incorrect choices.

The function’s routine comes after the listed characteristics. For this routine, I’ve used the BEGIN…END syntax to set up a compound statement, even though there is only one RETURN statement. Often your routine will include a compound statement—a block of one or more SQL statements—and I wanted to be sure you understood how to include them in your function definition. As with stored procedures, it’s not uncommon for developers to use a compound statement, even if it includes only a single SQL statement.

The RETURN statement defines a simple mathematic expression that multiples the lbs input parameter value by 0.45359237 to arrive at the number of kilograms for the specified weight. The result from this calculation is what is returned by the function when you run it.

The preceding example also includes two DELIMITER statements that surround the function definition. The first DELIMITER statement changes the delimiter to double forward slashes (//), and the second DELIMITER statement changes the delimiter back to a semi-colon (the default). As you saw in the previous article, this provides a way to pass the entire function definition to the server as a single statement.

Verifying a newly created stored function

After you run the CREATE FUNCTION statement, you can verify that it’s been added to the travel database by viewing it in Navigator, as shown in Figure 1. (You might need to refresh Navigator to see the new function.)

An image showing the Navigator. The lbs_to_kg function can be seen in the Functions folder

Figure 1. Viewing the function in Navigator

From Navigator, you can open the function definition in the Routine tab by clicking the wrench icon next to the function name. Figure 2 shows the function definition on the Routine tab. The CREATE FUNCTION statement is nearly identical to what you created, except that it now includes the DEFINER clause after the CREATE keyword.

An image showing the function definition in the dialog. CREATE DEFINER='root'@'localhost' FUNCTION 'lbs_to_kg'(lbs MEDIUMINT UNSIGNED) RETURNS mediumint unsigned DETERMINISTIC BEGIN RETURNS (lbs * 0.45359237); END

Figure 2. Viewing the function definition on the Routine tab

As you saw with views and stored procedures, the DEFINER clause specifies which account has been designated as the object creator. I ran the CREATE FUNCTION statement when I was signed in under the root account on my local MySQL instance, so that’s the username added to the definition. By default, MySQL uses the account of the user who runs the CREATE PROCEDURE statement, but you can specify a different account as long as it’s been granted adequate permissions.

You might have noticed that the function definition on the Routine tab does not include the DELIMITER statements or custom delimiter. However, if you were to update the definition and click Apply, Workbench would add those elements for you. (It would also add a DROP PROCEDURE statement that needs to run before the CREATE FUNCTION statement.)

Another way you can verify that the function has been created is to query the routines view in the INFORMATION_SCHEMA database:

SELECT * FROM information_schema.routines
WHERE routine_schema = 'travel';

The results should include the lbs_to_kg function, along with any other stored functions or stored procedures that have been created in the database. If you’re using the setup from the last article, your database might include the get_plane_info stored procedure.

In the preceding example, I included a WHERE clause that limits the results to the travel database. However, you can further limit the results by also specifying the function name in the WHERE clause and by specifying which column or columns to return. For example, the following SELECT statement limits the results to the routine_definition column and to the lbs_to_kg function in the travel database:

SELECT routine_definition
FROM information_schema.routines
WHERE routine_schema = 'travel'
  AND routine_name = 'lbs_to_kg';

The statement should now return only a single value, although it might be difficult to read. As you saw with stored procedures, you can view a value in its entirety in a separate window. Right-click the value directly in the results and click Open Value in Viewer. MySQL launches a window that displays the value, as shown in Figure 3. (Select the Text tab if it’s not already selected.)

An image showing the full definition of the function in a dialog. BEGIN RETURN (lbs * 0.45359237); END

Figure 3. Examining the function’s routine body in Viewer

As you can see, the window displays only the function’s routine body, which in this case, is a compound statement that includes a RETURN statement.

Using a stored function in a MySQL query

After you verify that your function has been created, you should check that it works as expected. One way to do this is to create a simple SELECT statement that does nothing but call the lbs_to_kg function. For example, the following SELECT statement includes only a SELECT clause, and that clause contains only one expression:

SELECT lbs_to_kg(132) AS max_kg;

The expression calls the lbs_to_kg function, passing in 132 as the parameter value. The expression also provides a name for the output column (max_kg). The statement should return a value of 60.

In many cases, you’ll want to use your stored function for more than just running it in a simple SELECT statement. For example, you can use a stored function to transform or augment a column’s values when retrieving data, which is what I’ve done in the following SELECT statement:

SELECT a.plane, max_weight AS max_lbs, 
  lbs_to_kg(max_weight) AS max_kg
FROM airplanes a INNER JOIN manufacturers m
  ON a.manufacturer_id = m.manufacturer_id
WHERE m.manufacturer = 'airbus'
ORDER BY a.plane;

The statement joins the airplanes and manufacturers tables based on the manufacturer_id column in each table. The statement’s SELECT clause includes an expression that uses the lbs_to_kg function to convert the max_weight column to kilograms and return a column named max_kg. The statement returns the results shown in Figure 4.

An image showing the results of running the query. Four rows returned. Plane, max_lbs, max_kg. In each row the lbs has been translated into kg

Figure 4. Using the stored function in your query

The results include the original weight (in pounds) in the max_lbs column and the weight in kilograms in the max_kg column after converting the max_weight values. By including both weights, you can quickly compare them to get a general sense of whether the function seems to be returning the expected results.

Updating a stored function in MySQL

As pointed out earlier, MySQL stored functions are similar to stored procedures in several ways. For example, they both support characteristics, input parameters, and the DEFINER clause. They’re also similar in another important way. You can alter only the characteristics. You cannot change the routine or any other statement elements. Instead, you must first drop the function and then re-create it, incorporating any new elements.

To drop a stored function, you can use the DROP FUNCTION statement, as shown in the following example:

DROP FUNCTION IF EXISTS lbs_to_kg;

The IF EXISTS clause is optional, but it’s a handy way to avoid generating errors when you try to drop a function. The clause can be particularly useful when you’re developing your database schema and you’re regularly updating the objects.

After you’ve dropped the function, you can modify the definition to meet your new requirements. For example, the following CREATE FUNCTION statement re-creates the lbs_to_kg function but this time adds a DECLARE statement and an IF construction to the compound statement:

DELIMITER //
CREATE FUNCTION lbs_to_kg(lbs MEDIUMINT UNSIGNED)
RETURNS VARCHAR(50) 
DETERMINISTIC
BEGIN
  DECLARE msg VARCHAR(50);
  IF lbs > 999999 THEN SET msg = 
    CONCAT(ROUND((lbs * 0.45359237), 0), 
            ' kg exceeds airport weight limits.');
  ELSEIF lbs >= 100000 AND lbs <= 999999 THEN SET msg = 
    CONCAT(ROUND((lbs * 0.45359237), 0), 
            ' kg exceeds runway weight limits.');
  ELSE SET msg = CONCAT(ROUND((lbs * 0.45359237), 0), 
            ' kg within weight limits.');
  END IF;
  RETURN msg;
END//
DELIMITER ;

The DECLARE statement declares the msg local variable and assigns it the VARCHAR data type. Notice that the RETURNS clause has also been updated to the VARCHAR data type to match the msg variable. The variable can then be used in the final RETURN statement to provide the function’s output value.

The compound statement also includes an IF statement. The statement starts with an initial conditional clause, which is followed by an ELSEIF clause and then an ELSE clause. Each clause implements the same logic based on the value of the lbs input parameter. If the lbs value falls within the specified range, the msg variable is set to a predefined value based on that range. (We’ll be covering conditional statements in more detail later in the series.)

The msg value is determined first by converting the lbs value to kilograms and then concatenating the results with a string (the message body). For example, if the lbs value is greater than 99999, the msg variable is set to the number of kilograms plus the message ‘ kg exceeds the airport weight limits.’

To help carry out this logic, each conditional clause also includes two built-in functions: ROUND and CONCAT. The ROUND function rounds the calculated kilograms to a whole number, and the CONCAT function concatenates the rounded kilograms with the specified text. For example, if the weight in pounds is 120,000, the IF statement will set the msg variable to ‘54431 kg exceeds runway weight limits.’ You can see this for yourself by running the following SELECT statement:

SELECT lbs_to_kg(120000) AS max_kg;

The statement should return the results shown in Figure 5.

An image showing the results of the query. max_kg 54431 kg exceeds the runway weight limits

Figure 5. Viewing the results returned by the updated stored function

You can also use the lbs_to_kg function in a more elaborate SELECT statement, just like you did earlier:

SELECT m.manufacturer, a.plane, 
  max_weight AS max_lbs, 
  lbs_to_kg(max_weight) AS max_kg
FROM airplanes a INNER JOIN manufacturers m
  ON a.manufacturer_id = m.manufacturer_id
ORDER BY m.manufacturer, a.plane;

Now each returned row includes one of the three messages in the max_kg column. The message is based on the number of pounds in the max_weight column, which is passed to the function through its parameter. Figure 6 shows the results returned by the SELECT statement.

An image showing the results of the query. One row for each plan is returned with the appropriate message that translated lbs to kg and then either exceeds runway weight limits, exceeds airport weight limits or within weight limits

Figure 6. Using a stored function in your query expressions

Your function can, of course, include a much more complex routine than what I’ve done here, but these examples should be enough to give you a sense of what you can do with stored functions and how valuable they can be when building your queries.

Altering a stored function in MySQL

As I mentioned earlier, the only elements of a stored function definition that you can alter are the characteristics. For this, you can use an ALTER FUNCTION statement. For example, the following statement adds a COMMENT characteristic and SQL SECURITY characteristic:

ALTER FUNCTION lbs_to_kg
COMMENT 'converts weight to kilograms and generates message'
SQL SECURITY INVOKER;

The COMMENT characteristic simply adds a comment that describes the function’s purpose. The SQL SECURITY characteristic instructs MySQL to run the routine under the security context of the user account that invokes the function rather than using the definer account (the default behavior).

After you run the ALTER FUNCTION statement, you can verify that the characteristics have been added by viewing the function definition on the Routine tab, as shown in Figure 7.

An images showing the new function definition in a dialog

Figure 7. Viewing the stored function definition on the Routine tab

The CREATE PROCEDURE statement now includes three characteristics—the one you added originally and the two you added when you ran the ALTER FUNCTION statement.

Working with stored functions in MySQL

Although stored functions are similar to stored procedures, they serve a distinctly different purpose: to return a value that can be used by an expression during its evaluation. For this reason, stored functions can be extremely useful and are well worth adding to your arsenal of tools, especially since they’re so easy to create and execute. However, they can also impact performance if not carefully implemented. For example, if your query returns thousands of rows of data, an overly complex function could bring your system to its knees as MySQL tries to apply the logic to each row. When used properly, however, stored functions can be incredibly beneficial, especially as you become more adept at building SQL queries.

 

The post Working with MySQL stored functions appeared first on Simple Talk.



from Simple Talk https://ift.tt/VatPLin
via