Home > Articles > Data > SQL Server

The Simplest SQL Notification Application: Stock Quotes

This chapter by Shyam Pather introduces you to the basics of SQL-NS and shows you how coding in this environment works.
This chapter is from the book

In this chapter, you'll see your first SQL-NS application. Think of this chapter as a tour: My intent is simply to show you around the various facilities that the platform offers so that you get a feel for the application model and the process of coding to it.

We will look at code in this chapter, but simply for the purpose of understanding the concepts behind the application. A line-by-line explanation of the code at this stage would drown out the simpler picture that I'm trying to show.

That said, I will gloss over (or in some cases, completely ignore) some parts of the code you will see; I'll just highlight those pieces of the code that illustrate particularly important parts of the application model. Subsequent chapters will cover the rest in detail.

The SQL-NS Application Model

SQL-NS can be used to build a variety of notification applications with different uses and for different application domains. But, when viewed from the highest level, all these notification applications conform to the same basic model, shown in Figure 3.1.

Data enters the application from the outside world. This data can be pulled in by the application, or pushed in by an external source. In SQL-NS terms, each piece of data is referred to as an event, because it represents some happening in the outside world that may potentially be of interest to some subscribers. An event may be a new price for a stock, notice of a new traffic incident, or a gate change for a flight.

Figure 3.1Figure 3.1 High-level view of a notification application.

The notification application maintains users' subscriptions; subscriptions are users' declarations of what kinds of events interest them. When events arrive, the application matches them with the subscriptions and produces a set of notifications. These notifications are delivered to the end users.

Events As Data

Events are just descriptions of some real-world "happening" that can be represented as data. For example, a change in the price of a stock (an event potentially of interest to a stock broker client) can be described as a piece of structured data containing a stock symbol field and a stock price field. A traffic incident event (for a traffic reporting application) might contain a field that describes the location of the incident and another describing the incident type (accident, road closure, weather warning, and so on).

Whatever the type of event, its description can be modeled as data. The structure of the data can be described with a schema that indicates the names of the fields and their data types. Given this schema, it's easy to construct a database table to store the event data. For example, stock events can be stored as rows in a table as shown in Figure 3.2.

Figure 3.2Figure 3.2 Modeling stock events as rows in a table.

Subscriptions As Data

Thinking of events as data is usually quite natural, but subscriptions can be modeled as data too. Think of the subscriptions to the stock application. Let's say that all subscriptions will have the form

"Notify me when the price of stock S goes above price target T."

where S represents some stock symbol and T represents a price target. So an example subscription might be

"Notify me when the price of stock XYZ goes above price target $50.00."

When the form of all the subscriptions is fixed as such, an individual subscription can simply be represented as a pair of values for S and T. Such subscriptions could be stored in a table as shown in Figure 3.3.

Figure 3.3Figure 3.3 Modeling stock subscriptions as rows in a table.

Each row identifies the subscriber and the stock symbol and price target of interest to them. For illustrative purposes, here the subscriber is just represented by a name, but in reality it may be a richer identifier.

NOTE

The stock quotes application we will build in this chapter supports the kinds of events and subscriptions discussed in the examples so far. The application allows subscribers to enter subscriptions for stocks in which they are interested. The application notifies them when those stocks cross the target prices that the subscribers specify.

For example, I could enter a subscription in this application that says, "Notify me when stock XYZ goes above $50." The application will receive a constant stream of stock price updates (representing changes in the market), and when an event indicating that the current price of XYZ is above $50 arrives, the application will send me a notification.

Matching Events with Subscriptions

As mentioned in Chapter 1, "An Overview of Notification Applications," the matching of events with subscriptions is the key function of the notification application. If the matching can be implemented efficiently, the application will scale to large volumes.

With events and subscriptions both represented as data, matching can be accomplished by means of a SQL join. Given the table structures in Figures 3.2 and 3.3 for events and subscriptions—and let's say that we called the events table Events and the subscriptions table Subscriptions—the following SQL statement would determine the matches:

SELECT S.Subscriber, E.StockSymbol, E.StockPrice
FROM   Events E JOIN Subscriptions S 
ON     E.StockSymbol = S.StockSymbol
WHERE  E.StockPrice >= S.PriceTarget 

This joins the stock events table with the subscriptions table on stock symbol and then selects rows where the stock price in the event is greater than or equal to the stock price target specified in the subscription. The set of rows returned by this query represents the notifications to be sent. For the particular example data shown previously, Figure 3.4 shows the results of the query.

Figure 3.4Figure 3.4 Results of matching events with subscriptions.

Note that only three of the four subscriptions matched: Jane's subscription specified a price target for PQS of 100.00, and because the stock price event for PQS said the price was only 95.30, the matching query did not return a row for Jane.

Each of the rows in the results table is the raw data for a notification to be sent. Thus, notifications too can be modeled as rows of data in a table. This data can later be packaged into a readable message and then delivered to the appropriate subscriber.

Scalability of the SQL-NS Application Model

The modeling of both events and subscriptions as data is a key innovation of SQL-NS and the basis for its capability to scale. Because both events and subscriptions are just rows in tables, SQL joins can be used to match them. In general, SQL joins are extremely efficient at matching large sets of data; more than 20 years of query processing and indexing innovation make this possible. As long as a reasonable join query can be written for a particular event and subscription schema (in most cases, one can), then the cost of matching (in terms of computing resources) will be low. Furthermore, this cost grows sublinearly with the amount of data. That is, if you double the number of events or subscriptions, the cost of matching does not double, but rather grows by some much smaller increment.

This model is different from that used by most other pub-sub systems. Most other systems model individual subscriptions as queries, rather than data. The simplest of these systems evaluates the subscription queries one-by-one for a given set of events. This strategy is expensive, and, as the number of subscriptions or events grows, the cost of evaluation grows linearly.

NOTE

To be absolutely clear, the SQL-NS application model uses queries to evaluate subscriptions. But, it does not model each individual subscription as a query. Instead, in the SQL-NS application model, there is one query for each subscription type. This query evaluates all subscriptions of that type at once. This is the key differentiator between SQL-NS and other pub-sub systems.

To improve performance, the more sophisticated of the systems that model subscriptions as queries try to analyze the subscription queries for similarity and then evaluate the similar parts in a set-oriented fashion. Query analysis can be difficult in general, but deducing similarity can be especially difficult when the queries can be arbitrarily complex. In many cases, systems that model subscriptions as queries can't do much better than one-at-a-time evaluation.

In the SQL-NS model of subscriptions as data, the application developer actually enforces the similarity between subscriptions. By fixing the form of the subscriptions, the developer is providing a subscription template. This template has parameters that can vary per subscription. Individual subscriptions are then just sets of values for these parameters. In the stock example, the subscription template defines the structure of the subscription query, and the individual subscriptions just supply values for the stock symbol and target price.

The obvious drawbacks to this approach are that all users' subscriptions must have the same structure, and the only kinds of subscriptions that users can enter are those for which the application developer has provided a template. It is true that modeling a subscription as a query, as other systems do, allows for greater end user flexibility because each user can enter any arbitrary subscription. For example, in a system that models subscriptions as queries, one user might have a simple subscription such as

"Notify me when the price of stock XYZ goes above price target 50.00."

and another might write a subscription query that says

"Notify me when the price of stock XYZ goes above price target 50 and the trading volume is greater than 100,000 and there are favorable news stories featuring stock symbol XYZ."

It's worth questioning whether such flexibility is really needed in your application. Do your users really need to be able to enter arbitrarily complex subscriptions? Does each user need to be able to enter a different kind of subscription? Or can you devise a set of subscription templates that cover the overwhelming majority of subscriptions users will want to enter? Note that SQL-NS subscription templates can be rich and support complex subscriptions like the preceding one. The template-based approach doesn't really restrict you as a developer: You can easily build complex subscription templates if you need them in your application. However, it does restrict your users: They can only create subscriptions for which you have provided templates.

SQL-NS allows you to support several types of subscriptions in a single application, by providing a template and a set of parameters for each subscription type. Experience has shown that in the vast majority of applications, developers can predict what subscriptions users will want to enter and create subscription classes for those. Doing so usually results in some powerful applications that are immediately useful to most users. Often, the lack of flexibility in authoring subscription queries is not even noticed by the end users.

Programming to the SQL-NS Application Model

In summary, the SQL-NS application model views events and subscriptions as data, and uses SQL joins to match them. As a developer building an application on the SQL-NS platform, you provide two things: schemas and logic that define the application's behavior and a component configuration that determines how the SQL-NS execution engine components actually run the application. Both the schemas and logic, as well as the component configuration, are provided in an XML document called an Application Definition File (ADF).

In the schemas and logic part of the ADF, you specify the schema for the events and subscriptions and the SQL join logic that matches them. Also, you specify a schema for the notification data that the join produces.

Each of the schemas is a description of the size and shape of a certain kind of data: You provide the names of the fields and their data types, much as you would if you were defining a SQL table. The schema for the events specifies what the data your application receives from the outside will look like. The schema for the subscription data describes the parameters to the subscription template. The schema for the notification data describes the fields that result from the join that matches events and subscriptions.

After the event and subscription data schemas are defined, you also provide the SQL join statements used to match them. In writing the join statement, you can apply operations to the event and subscription data to determine whether they match. Effectively, you are defining what a "match" means for your particular event and subscription types. In the previous stock example, a match meant that the stock symbol in the event was the same as the stock symbol in the subscription, and the stock price was equal to or greater than the target price specified in the subscription.

In the component configuration section of the ADF, you specify how the SQL-NS engine components should run your application. You can specify how the components are distributed across various servers, what resources they should use, and when they should run.

You compile your finished ADF using the SQL-NS compiler. This produces a database that is used to run the application, containing tables for events and subscriptions and stored procedures that execute the join logic you provided. Finally, you register an instance of the SQL-NS Windows Service to host the engine components that run your application. This service coordinates the various running components of your application and their interactions with the database, as shown in Figure 3.5.

Figure 3.5Figure 3.5 The ADF is compiled into database structures, and a Windows Service runs the application.

NOTE

Figure 3.5 shows only the parts of the application created by compiling the ADF and registering an instance of the Windows Service. Other important parts of a complete, running application—such as the systems that submit events, the subscription management interface, and the delivery systems—are not shown.

In this chapter, we're going to build the stock quotes application. We'll define the schema of the event data, the schema of the subscription data, the SQL logic that matches them, and the schema of the final notification data. Although there are other parts to the application, these are the parts we'll really focus on in this chapter because they form the application's core and are the most illustrative of the SQL-NS application model.

NOTE

To work through the steps in this chapter, you need to set up your development environment as described in Chapter 2, "Getting Set Up." If you have not already done this, go through the steps in that chapter before proceeding.

The source code for this chapter is located in the Chapter03 directory under the source code base directory. Several files are in the folder: Some are discussed here; others are explained in later chapters. For now, the file to focus on is the stock application's ADF, which can be found in the Stock folder under Chapter03. The file is called ApplicationDefinition.xml. Open this file in your XML editor and refer to it as you read through this chapter.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020