smartyfy.mrindigi.com

Databases & SQL Master Course — 171. Views and Interface Contracts

Lesson 171 Views and Interface Contracts

Prerequisites and objectives

Complete warehouse publication and relational projections. You will define an explicit view interface, observe its dependence on current base data, test SQLite’s ordinary view write restriction, and distinguish a stable column contract from performance, authorization, and historical-snapshot guarantees.

A view names a query interface

The catalog view exposes active products with three named columns: product identity, display name, and price in cents. Internal cost is excluded. The explicit column list makes the intended names clear even if the underlying expressions or base-column names later change.

An ordinary view stores a query definition rather than an independent frozen result. Reading it evaluates its meaning against the database state visible to that statement and transaction. It does not automatically preserve yesterday’s catalog, precompute every result, or update a separate cache.

Document the interface beyond its column names. State one-row meaning, units, NULL behavior, filters, key expectations, and authorization assumptions. A view that keeps the same names but changes from active products to all products has changed its semantic contract even if client code still parses the output.

CREATE TABLE lab_product171(id INTEGER PRIMARY KEY,title TEXT NOT NULL,price_cents INTEGER NOT NULL CHECK(price_cents>=0),active INTEGER NOT NULL CHECK(active IN (0,1)),internal_cost_cents INTEGER NOT NULL);
INSERT INTO lab_product171 VALUES(1,'Pen',100,1,40),(2,'Pad',200,0,90);
CREATE VIEW lab_catalog171(product_id,display_name,price_cents) AS SELECT id,title,price_cents FROM lab_product171 WHERE active=1;
Catalog interface contract
Aspect Promise Outside this promise
Rows One row per active product Inactive products are omitted
Columns Identity, display name, price in cents Internal cost is not projected
Freshness Current transaction-visible base state No stored historical snapshot
Writes Read through the ordinary SQLite view No automatic writable-view behavior

Worked practice

Exercise 1

Read the public projection with an explicit outer ordering.

Worked solution
-- Connection A
SELECT product_id,display_name,price_cents FROM lab_catalog171 ORDER BY product_id;
SELECT name FROM pragma_table_info('lab_catalog171') ORDER BY cid;

Only the active Pen appears, and the interface has the three declared names. The caller supplies ORDER BY because a relational result has no guaranteed presentation order without an applicable ordering clause. Do not treat physical base-table order as part of the view contract.

Exercise 2

Change base data inside a transaction and observe the view immediately.

Worked solution
-- Connection A
BEGIN;
UPDATE lab_product171 SET price_cents=150 WHERE id=1;
UPDATE lab_product171 SET active=1 WHERE id=2;
SELECT product_id,price_cents FROM lab_catalog171 ORDER BY product_id;
ROLLBACK;
SELECT product_id,price_cents FROM lab_catalog171 ORDER BY product_id;

The view reflects the connection’s pending changes, then returns to the original visible state after rollback. No refresh statement is needed for this ordinary view. Visibility still follows transaction isolation; another connection does not gain access to these uncommitted changes merely because it reads the same view.

Exercise 3

Attempt an ordinary UPDATE through the SQLite view.

Worked solution
-- Connection A
UPDATE lab_catalog171 SET price_cents=0 WHERE product_id=1;
SELECT price_cents FROM lab_product171 WHERE id=1;

SQLite rejects the write because an ordinary view is read-only. An INSTEAD OF trigger can define custom write behavior, but that is additional logic with its own validation and tests. Other engines may permit automatically updatable views under specific rules; do not generalize their behavior to SQLite.

Exercise 4

Rehearse a base-column rename while preserving the explicit view names.

Worked solution
-- Connection A
BEGIN;
ALTER TABLE lab_product171 RENAME COLUMN title TO label;
SELECT product_id,display_name,price_cents FROM lab_catalog171 ORDER BY product_id;
SELECT name FROM pragma_table_info('lab_catalog171') ORDER BY cid;
ROLLBACK;

The tested modern SQLite version updates the dependent view reference during the supported rename, while the explicit output name remains display_name. This demonstrates one compatible migration, not every possible schema edit. Inspect definitions and rerun contract tests after changes rather than assuming dependency rewriting always succeeds.

Use a view as a maintained boundary

Keep the view definition in a reviewed migration artifact and track its consumers. A change to filtering, joins, rounding, or NULL substitution can break business meaning without changing the number of columns. Version an interface when incompatible behavior must coexist during a transition.

Explicit projections reduce accidental coupling to new base columns. SELECT star inside a published view or consuming application can expose added fields or change result shape unexpectedly, depending on engine behavior and when definitions are resolved. List the intended fields and test their names and meanings.

Views can also hide join complexity, but they do not eliminate its cardinality risks. A view joining a product to several tags may produce multiple rows per product. State its grain and test it rather than assuming a view is always one-to-one with a base entity.

Keep security and performance claims specific

Omitting internal cost from this projection does not confine a process that has unrestricted SQLite file access and can query the base table directly. A server database may enforce grants or specialized view security behavior, but those depend on the engine, definition, owner, and runtime role. An interface convention is not automatically a complete access-control boundary.

Likewise, a view is not inherently a performance optimization. The optimizer may transform its query, but the underlying joins, filters, scans, and sorts still need appropriate data design and measurement. Inspect the plan for the consuming query and verify results before tuning.

A view has no ordinary value-parameter list. Callers can apply bound predicates to its columns, or use another documented routine mechanism when parameterized database logic is required. Do not construct arbitrary SQL fragments to make a view behave like a function.

Test the contract as consumers use it

Include active and inactive records, boundary prices, expected NULLs if allowed, duplicate-producing joins, and schema migrations. Test the outer query’s ordering and filters. Check that forbidden fields are absent from the intended response, while separately testing the actual authorization system.

The view’s dependencies also belong in backup and restore verification. Restoring a table without a required view can leave the application unusable even when every data row is present. Conversely, restoring a view definition without its dependencies is not a complete interface recovery.

Pitfalls and summary

Publish explicit names and semantic promises, not just convenient SELECT text. Distinguish current query evaluation from persisted results, read-only SQLite views from engine-specific writable views, and projection from enforced authorization. Maintain and test the interface whenever its underlying schema or business meaning changes.

Knowledge check

Question 1

What does the ordinary catalog view store?

  1. A separate result copied whenever the source transaction commits
  2. A snapshot retained from the first SELECT
  3. A query definition rather than an independent frozen result
  4. A cached result requiring an explicit refresh
Answer and explanation

C. Ordinary views evaluate against transaction-visible base data; they do not maintain an independent result copy.

Question 2

What does an explicit view output-name list establish?

  1. A named interface independent of incidental expression names
  2. Compatibility with every future base-schema change
  3. Enforced data types for each computed expression
  4. A stable presentation order for returned rows
Answer and explanation

A. The list controls column names, while type behavior, semantics, and ordering require separate contracts.

Question 3

Why did the direct view UPDATE fail in this SQLite fixture?

  1. The price value zero violates the base CHECK
  2. SQLite allows view writes only when every base column is projected
  3. The WHERE filter makes an otherwise writable SQLite view read-only
  4. No INSTEAD OF trigger defines writes for the read-only view
Answer and explanation

D. SQLite ordinary views are read-only; the nonnegative price constraint would permit zero.

Question 4

Does the projection restrict a process with unrestricted SQLite file access?

  1. Yes; creating the view revokes direct base-table reads
  2. Yes; an explicit view column list becomes a file-level access policy
  3. No; that process may query the base table directly
  4. Yes; the view filter applies automatically to base-table queries
Answer and explanation

C. Projection shapes an interface; it does not revoke unrestricted access to the underlying SQLite file.

Question 5

Which change breaks the active-product contract while preserving column names?

  1. Renaming a base column while preserving the same output and meaning
  2. Including inactive products in the returned rows
  3. Adding an index without changing the view query
  4. Adding an unprojected base column without changing the view definition
Answer and explanation

B. The promised row filter is part of the interface, independently of its names.

Execution scope

These scenarios were executed with SQLite 3.53.1 using separate connections to newly created disposable local database files. No existing or external database was used. Each scenario starts from a fresh fixture. Python was an internal verification harness, not a learner prerequisite. Follow the labeled connection order in SQL clients that open the same disposable file.

Primary references