使用 Firebase SQL Connect (網頁版) 建構即時交易應用程式

1. 事前準備

在本程式碼研究室中,您將整合 Firebase SQL Connect 與 Cloud SQL 資料庫,建構 Friendly Exchange,這是一個即時表情符號股市網頁應用程式。

完成的應用程式會展示進階 SQL Connect 功能,包括:

  • 原生 SQL:使用 _execute_select 安全地執行複雜的資料操縱語言 (DML) 陳述式和通用資料表運算式 (CTE)。
  • SQL 檢視區塊:使用 @view 指令建立嚴格的型別安全 GraphQL 物件,並以動態 Postgres 查詢做為後端。
  • 即時訂閱:使用 @refresh 觸發條件,讓前端 UI 保持同步。
  • 不可分割的交易:串連多項作業,並使用 @transaction@check 驗證狀態。
  • (選用) 地理空間和向量搜尋:運用 PostGIS 和 pgvector,找出使用者座標附近的熱門資產,並執行語意搜尋。
  • (選用) 自訂解析器:將自訂 Cloud Run 邏輯連結至 GraphQL 結構定義,產生 AI 交易標題。

必要條件

您需要深入瞭解 JavaScript/TypeScript、React 和基本 SQL 語法。

課程內容

  • 如何使用原生 SQL 縮小宣告式 GraphQL 與原始 PostgreSQL 邏輯之間的差距。
  • 如何將 PostGIS 等 Postgres 擴充功能直接整合至資料庫查詢。
  • 如何使用原子 @transaction 區塊強制執行複雜邏輯。
  • 如何為排行榜和統計資料建立類型安全的 @views
  • 如何使用 @refresh 設定即時訂閱。

軟硬體需求

  • Git
  • Visual Studio Code
  • 安裝 Node.js
  • 採用即付即用 Blaze 定價方案的 Firebase 專案 (自訂解析器和 Vertex AI 必須使用此方案)。

2. 設定開發環境

這個階段會引導您設定前端,並為進階功能設定 Cloud SQL 執行個體。

  1. 複製專案存放區,並安裝應用程式所需的依附元件:
git clone https://github.com/firebaseextended/codelab-dataconnect-web
cd codelab-dataconnect-web
git switch emoji-init
npm install
  1. 使用 Visual Studio Code 開啟複製的資料夾,然後安裝 Firebase SQL Connect Visual Studio 擴充功能
  2. 在終端機中,確認 Firebase CLI 已完全更新 (這是使用 @refresh 和原生 SQL 等新功能時的必要步驟):
npm uninstall -g firebase-tools
npm install -g firebase-tools
firebase login
firebase use your-project-id
firebase init

(選取代管、驗證和 SQL 連線)。

產生 SQL Connect SDK:執行下列指令:

firebase dataconnect:sdk:generate
  1. 將網頁應用程式連結至 Firebase 專案:使用 Firebase 主控台在 Firebase 專案中註冊網頁應用程式:
    1. 開啟專案,然後按一下「Add App」 (選取「Web」圖示)。
    2. 暫時忽略 SDK 設定和設定設定,但請務必複製產生的 firebaseConfig 物件。
    3. 在程式碼編輯器中開啟 lib/firebase.tsx,並將現有預留位置替換為您剛才複製的設定:
const firebaseConfig = {
  apiKey: "API_KEY",
  authDomain: "PROJECT_ID.firebaseapp.com",
  projectId: "PROJECT_ID",
  storageBucket: "PROJECT_ID.firebasestorage.app",
  messagingSenderId: "SENDER_ID",
  appId: "APP_ID"
};
  1. 執行開發伺服器:
npm run dev

3. 查看範例程式碼集

在本節中,您將探索應用程式入門程式碼庫的重要領域。雖然您會從頭開始編寫結構定義和查詢,但瞭解前端如何連線以與 SQL Connect 互動,會很有幫助。

資料夾和檔案結構

dataconnect/ 目錄

這個資料夾包含後端定義,從資料庫結構到應用程式可執行的特定 SQL 查詢,應有盡有。

  • schema/schema.gql:您將使用標準 GraphQL 型別定義基本 Postgres 資料表。
  • schema/views.gql:您將使用 @view 指令定義複雜的唯讀 SQL 檢視區塊 (例如排行榜)。
  • friendly-exchange/queries.gqlmutations.gql:你的「連結器」。您可以在這裡定義應用程式允許的確切查詢和原生 SQL (_execute_select)。
  • dataconnect.yaml:設定檔,用於指定 SDK 生成和 Cloud SQL 部署設定。

lib/ 目錄

包含應用程式邏輯、驗證,以及與 Firebase SQL Connect SDK 的互動。

  • firebase.tsx:處理 Firebase 應用程式、Auth 和 SQL Connect 執行個體的初始化作業。
  • ExchangeService.tsx:這是 React 元件與資料庫之間的橋樑。它會將產生的 SDK 函式 (例如 buyStocksellStock) 包裝在標準非同步函式中,以處理錯誤擷取、商業邏輯和 Toast 通知。

產生的 SDK

在 SQL Connect 中編寫查詢或變動時,VS Code 擴充功能會自動產生強型別 SDK。在這個專案中,前端會直接從 @dataconnect/generated 匯入這些函式。

4. 定義表情符號交換的結構定義

在本節中,您將定義交易應用程式中主要實體的結構和關係。UserEmojiStockOwnershipEventPriceHistory 等實體會對應至資料庫表格,並使用 Firebase SQL Connect 和 GraphQL 結構定義指令建立關係。

完成這個結構定義後,您的應用程式就能處理所有事項,包括執行買賣交易、更新全球排行榜,以及繪製當地地理空間趨勢。

核心實體和關係

  • 表情符號:包含符號、名稱、價格和趨勢等重要詳細資料,應用程式會使用這些資料顯示市場。
  • 使用者:追蹤交易者的個人資料、可用點數 (貨幣),以及用於掃描當地雷達的地理座標。
  • 關係:StockOwnership聯結資料表會追蹤特定使用者擁有特定表情符號的確切分享次數。EventPriceHistory 類型會做為不可變的帳本,記錄市場影響和歷史價位。

設定使用者表格

User 類型定義系統中的交易人,追蹤其餘額、角色和實際位置,以供地理空間查詢。

複製以下程式碼片段,然後貼到 dataconnect/schema/schema.gql 檔案中:

# Users
# user-stockOwnership is a one-to-many relationship, user-events is a one-to-many relationship
# Utilizes the Firebase Auth uid expression as the primary key
type User @table {
  id: String! @default(expr: "auth.uid")
  username: String!
  profileImage: String
  role: String! @default(value: "USER")
  points: Float! @default(value: 100.0)
  city: String @default(value: "Las Vegas")
  latitude: Float @default(value: 36.1699)
  longitude: Float @default(value: -115.1398)
}

重點回顧:

  • id:使用 @default(expr: "auth.uid") 直接繫結至 Firebase 驗證。這可確保資料庫身分和 Auth 身分安全無虞地 1:1 對應,防止使用者偽造 ID。
  • points:用於交易的虛擬貨幣,新使用者預設為 100.0

設定表情符號表格

Emoji 類型會定義交易的主要資產,包括標準文字搜尋的欄位。

複製以下程式碼片段,然後貼到 dataconnect/schema/schema.gql 檔案中:

# Emojis
# emoji-stockOwnership is a one-to-many relationship, emoji-priceHistory is a one-to-many relationship
# Implements @searchable directives for full-text search
type Emoji @table {
  id: UUID! @default(expr: "uuidV4()")
  symbol: String!
  name: String! @searchable
  tags: [String!]
  description: String! @searchable
  currentPrice: Float! @default(value: 10.0)
  trend: Float! @default(value: 0.0)
}

重點回顧:

  • name & description:使用 @searchable 指令,針對標準全文搜尋最佳化這些資料欄。

設定 StockOwnership 資料表

StockOwnership 型別是聯結資料表,可處理使用者與所擁有表情符號之間的多對多關係。複製以下程式碼片段並貼到 dataconnect/schema/schema.gql 檔案中:

# Join table for many-to-many relationship between users and emojis
# The 'key' param signifies the primary key(s) of this table
# In this case, the keys are [user, emoji], the generated fields of the reference types
type StockOwnership @table(key: ["user", "emoji"]) {
  user: User!
  emoji: Emoji!
  shares: Int! @default(value: 0)
}

重點回顧:

  • key: ["user", "emoji"]:建立複合主鍵。使用者無法為同一表情符號建立兩筆不同的記錄,系統會強制確保每對表情符號的記錄都是獨一無二。
  • 隱含參照:直接參照 UserEmoji 型別時,SQL Connect 會在幕後自動產生外部鍵 userId: String!emojiId: UUID!

設定 Event 和 PriceHistory 資料表

這些類型代表應用程式的分類帳,會記錄確切發生的情況和價格變動。複製最終程式碼片段並貼到 dataconnect/schema/schema.gql 檔案中:

# Events
# Event-User is a many-to-one relationship, Event-Emoji is a many-to-one relationship
# Evaluates the createdAt timestamp purely on the server side using the request.time expression
type Event @table {
  id: UUID! @default(expr: "uuidV4()")
  user: User!
  emoji: Emoji!
  impact: Float!
  description: String!
  createdAt: Timestamp! @default(expr: "request.time")
}

# Price History
# PriceHistory-Emoji is a many-to-one relationship
type PriceHistory @table {
  id: UUID! @default(expr: "uuidV4()")
  emoji: Emoji!
  price: Float!
  recordedAt: Timestamp! @default(expr: "request.time")
}

重點回顧:

  • createdAtrecordedAt:使用 @default(expr: "request.time") 自動設定資料庫交易發生的確切時間。這樣可防止用戶端操控時間戳記。

自動產生的欄位和預設值

結構定義會依賴 @default(expr: "uuidV4()")@default(expr: "auth.uid") 等運算式自動產生專屬 ID,並強制執行擁有權,不必由用戶端應用程式提供。

5. 擷取市場和使用者資料

在本節中,您會將模擬市場資料插入資料庫,然後實作連接器 (查詢) 和 TypeScript 程式碼,在整個網頁應用程式中呼叫這些連接器。完成後,您的應用程式就能直接從資料庫動態擷取及顯示即時表情符號市集、使用者個人資料和排行榜。

插入模擬市場和使用者資料

  1. 在 VSCode 中開啟 dataconnect/seed.gql
  2. 確認 Firebase SQL Connect 擴充功能中的模擬器正在執行 (或已連線至 Cloud SQL 執行個體)。
  3. 檔案頂端應會顯示「Run (local)」或「Run (Production)」CodeLens 按鈕。按一下這個按鈕,即可將模擬表情符號資料和初始價格記錄插入資料庫。
  4. 檢查 SQL Connect Execution 終端機,確認資料已成功新增。

實作基本查詢

首先,請查詢您在結構定義中定義的標準資料表。

  1. 開啟 dataconnect/friendly-exchange/queries.gql
  2. 新增下列查詢,以擷取資訊主頁資料、使用者個人資料和基本價格記錄:
# Get dashboard data including top emojis by price and recent market events
query GetDashboardData
@auth(
  level: PUBLIC
  insecureReason: "This operation is safe to expose to the public."
) {
  emojis(orderBy: [{ currentPrice: DESC }]) {
    id
    symbol
    name
    description
    currentPrice
    trend
  }
  events(orderBy: [{ createdAt: DESC }], limit: 15) {
    id
    description
    impact
    createdAt
    user {
      username
      profileImage
    }
    emoji {
      symbol
    }
  }
}

# Get current authenticated user profile and their stock ownership using auth.uid
query GetUserProfile @auth(level: USER) {
  user(id_expr: "auth.uid") {
    points
    username
    profileImage
    role
    stockOwnerships_on_user {
      shares
      emoji {
        id
        symbol
        currentPrice
        name
      }
    }
    city
    latitude
    longitude
  }
}

# Get price history for a specific emoji ordered by time
query GetPriceHistory($emojiId: UUID!, $limit: Int)
@auth(
  level: PUBLIC
  insecureReason: "This operation is safe to expose to the public."
) {
  priceHistories(
    where: { emojiId: { eq: $emojiId } }
    orderBy: [{ recordedAt: ASC }]
    limit: $limit
  ) {
    price
    recordedAt
  }
}

重點回顧:

  • emojis() / events()系統會自動產生 GraphQL 查詢欄位,直接從資料表擷取資料。
  • id_expr: "auth.uid"擷取與目前已驗證的 Firebase 使用者權杖相符的使用者設定檔,確保存取安全無虞。
  • _on_可直接存取具有外鍵關係的相關聯型別中的欄位。stockOwnerships_on_user 會在單一查詢中擷取使用者的整個投資組合。
  • insecureReason將作業公開給 PUBLIC 時為必填。明確記錄為何這項資料可安全公開,不必經過驗證。

建立型別安全 SQL 檢視區塊

撰寫自訂 SQL 前,請務必瞭解 Firebase SQL Connect 處理查詢的不同方式:

  • 標準 GraphQL:最適合基本 CRUD 和簡單關係,並提供嚴格的端對端型別安全。
  • SQL 檢視畫面 (@view):最適合用於唯讀的複雜 SQL (例如使用視窗函式的排行榜),您仍希望將嚴格的型別安全 GraphQL 物件傳回給用戶端。
  • 原生 SQL (_execute / _select):最適合直接執行 DML、CTE 或 PostGIS 擴充功能。您會以嚴格的編譯時間型別,換取執行時間的最高彈性 (傳回動態 JSON)。

如要建立排行榜和走勢圖,我們需要計算移動平均值並為使用者排名。這是 @view 的用途。

  1. 開啟 dataconnect/schema/views.gql
  2. 新增下列檢視畫面,計算伺服器上的必要統計資料:
# Rank users on a leaderboard based on their total net worth
type TopTrader
@view(
  sql: """
  SELECT
    u.id,
    u.username,
    u.profile_image,
    (u.points + COALESCE(SUM(so.shares * e.current_price), 0)) AS net_worth,
    RANK() OVER (ORDER BY (u.points + COALESCE(SUM(so.shares * e.current_price), 0)) DESC) AS rank
  FROM "user" u
  LEFT JOIN stock_ownership so ON u.id = so.user_id
  LEFT JOIN emoji e ON so.emoji_id = e.id
  WHERE u.id != 'system_market_maker'
  GROUP BY u.id, u.username, u.profile_image, u.points
  """
) {
  id: String
  username: String
  profileImage: String
  netWorth: Float
  rank: Int
}

# Identify the top shareholder (whale) for each emoji and their total ownership percentage
type EmojiWhaleStat
  @view(
    sql: """
    WITH total_shares AS (
      SELECT emoji_id, SUM(shares) AS total_supply
      FROM stock_ownership WHERE shares > 0 GROUP BY emoji_id
    ),
    ranked_holders AS (
      SELECT
        so.emoji_id, u.username AS whale_username, u.profile_image AS whale_profile_image,
        so.shares AS whale_shares, ts.total_supply,
        ROUND((so.shares::DECIMAL / NULLIF(ts.total_supply, 0)) * 100, 2) AS whale_percentage,
        RANK() OVER (PARTITION BY so.emoji_id ORDER BY so.shares DESC) AS holder_rank
      FROM stock_ownership so
      JOIN "user" u ON u.id = so.user_id
      JOIN total_shares ts ON ts.emoji_id = so.emoji_id
      WHERE so.shares > 0
    )
    SELECT emoji_id, whale_username, whale_profile_image, whale_shares, total_supply, whale_percentage
    FROM ranked_holders WHERE holder_rank = 1
    """
  ) {
  emojiId: UUID
  whaleUsername: String
  whaleProfileImage: String
  whaleShares: Int
  totalSupply: Int
  whalePercentage: Float
}

# Calculate the moving average of historical prices for each emoji
type EmojiHistoryStat
  @view(
    sql: """
    SELECT
      emoji_id, price, recorded_at,
      AVG(price) OVER (PARTITION BY emoji_id ORDER BY recorded_at ROWS BETWEEN 4 PRECEDING AND CURRENT ROW) as moving_average
    FROM price_history
    """
  ) {
  emojiId: UUID
  price: Float
  recordedAt: Timestamp
  movingAverage: Float
}

# Combine recent price updates and major news events into a single chronological feed
type TickerFeed
  @view(
    sql: """
    WITH latest_prices AS (
      SELECT emoji_id, MAX(recorded_at) as last_trade_time
      FROM price_history GROUP BY emoji_id
    )
    SELECT
      'PRICE' as type, e.symbol, e.name, e.current_price, e.trend,
      '' as description, lp.last_trade_time as event_time
    FROM emoji e JOIN latest_prices lp ON e.id = lp.emoji_id
    UNION ALL
    SELECT
      'NEWS' as type, e.symbol, '' as name, 0 as current_price, 0 as trend,
      ev.description, ev.created_at as event_time
    FROM event ev JOIN emoji e ON ev.emoji_id = e.id
    """
  ) {
  type: String
  symbol: String
  name: String
  currentPrice: Float
  trend: Float
  description: String
  eventTime: Timestamp
}

# Retrieve the 15 most recent price points for each emoji to render sparkline charts
type EmojiSparkline
  @view(
    sql: """
    WITH RankedPrices AS (
      SELECT
        emoji_id, price, recorded_at,
        ROW_NUMBER() OVER(PARTITION BY emoji_id ORDER BY recorded_at DESC) as rn
      FROM price_history
    )
    SELECT emoji_id, price, recorded_at
    FROM RankedPrices WHERE rn <= 15 ORDER BY recorded_at ASC
    """
  ) {
  emojiId: UUID
  price: Float
  recordedAt: Timestamp
}

現在,請開啟 dataconnect/friendly-exchange/queries.gql,並取代 TODO,從新檢視畫面擷取資料:

# Get emoji whale statistics to identify top shareholders from emojiWhaleStats view
query GetEmojiWhaleStats
@auth(
  level: PUBLIC
  insecureReason: "This operation is safe to expose to the public."
) {
  emojiWhaleStats {
    emojiId
    whaleUsername
    whaleProfileImage
    whaleShares
    totalSupply
    whalePercentage
  }
}

# Get historical price and moving average stats for a specific emoji from emojiHistoryStats view
query GetEmojiHistoryStats($emojiId: UUID!)
@auth(
  level: PUBLIC
  insecureReason: "This operation is safe to expose to the public."
) {
  emojiHistoryStats(
    where: { emojiId: { eq: $emojiId } }
    orderBy: [{ recordedAt: ASC }]
    limit: 50
  ) {
    price
    movingAverage
    recordedAt
  }
}

# List top traders ordered by rank from topTraders view
query GetTopTraders
@auth(
  level: PUBLIC
  insecureReason: "This operation is safe to expose to the public."
) {
  topTraders(orderBy: [{ rank: ASC }]) {
    id
    username
    profileImage
    netWorth
    rank
  }
}

# Get chronological market ticker feed of recent events from tickerFeeds view
query GetChronologicalTicker
@auth(
  level: PUBLIC
  insecureReason: "This operation is safe to expose to the public."
) {
  tickerFeeds(orderBy: [{ eventTime: DESC }], limit: 30) {
    type
    symbol
    name
    currentPrice
    trend
    description
    eventTime
  }
}

# Get simple price points for rendering emoji sparkline charts from emojiSparklines view
query GetEmojiSparklines
@auth(
  level: PUBLIC
  insecureReason: "This operation is safe to expose to the public."
) {
  emojiSparklines {
    emojiId
    price
    recordedAt
  }
}

重點回顧

  • @view在伺服器上封裝複雜的資料庫邏輯,同時嚴格輸入用戶端程式碼。SQL Connect 會將 @view 型別的 GraphQL 欄位對應至 SELECT 陳述式傳回的資料欄。
  • 唯讀:檢視畫面沒有主鍵,無法直接變動。
  • 查詢產生:請注意,topTraders()emojiSparklines() 的運作方式與查詢標準資料表完全相同。

導入搜尋查詢

SQL Connect 會自動為結構定義中標有 @searchable 指令的任何欄位,產生標準搜尋查詢。

新增下列查詢至 dataconnect/friendly-exchange/queries.gql,啟用全文搜尋功能:

# Search emojis using full-text search query
query SearchEmojis($query: String)
@auth(
  level: PUBLIC
  insecureReason: "This operation is safe to expose to the public."
) {
  emojis_search(query: $query) {
    id
    symbol
    name
    description
    currentPrice
    trend
  }
}

重點回顧

  • emojis_search您在 Emoji 結構定義中對 namedescription 欄位套用 @searchable,因此系統自動建立查詢欄位。

產生 SDK

由於您已在 GraphQL 檔案中定義新的查詢和檢視畫面,因此必須執行 SDK 產生器,TypeScript 前端才能安全地使用這些查詢和檢視畫面。

開啟終端機並執行:

firebase dataconnect:sdk:generate

在網頁應用程式中整合查詢

Firebase SQL Connect 編譯器會根據 .gql 檔案產生 SDK。由於這是即時應用程式,您會在多個元件中使用 subscribe 方法和產生的查詢參照。

將下列檔案中的空白 useEffect 區塊,替換成以下邏輯:

1. 首頁 (

app/page.tsx

)

import { subscribe } from "@firebase/data-connect";
import {
  getDashboardDataRef,
  searchEmojisRef,
  getChronologicalTickerRef,
  getUserProfileRef,
} from "@dataconnect/generated";

// Inside the Home component:
  useEffect(() => {
    // Subscribe to realtime updates for the main market dashboard data including top emojis and recent events
    const unsubscribe = subscribe(
      getDashboardDataRef(),
      (res) => {
        if (res.data) setDashboardData(res.data);
        setIsDashboardLoading(false);
      },
      (err) => {
        console.error("Dashboard Realtime Error:", err);
        setIsDashboardLoading(false);
      },
    );
    return () => unsubscribe();
  }, [user]);

  useEffect(() => {
    // Subscribe to a realtime chronological ticker feed combining recent price updates and major news events
    const unsubscribe = subscribe(
      getChronologicalTickerRef(),
      (res) => {
        if (res.data) setTickerData(res.data);
      },
      (err) => console.error("Ticker Realtime Error:", err),
    );
    return () => unsubscribe();
  }, []);

  useEffect(() => {
    if (loading || !user) return;
    // Subscribe to realtime updates for the authenticated user's profile and stock ownership
    const unsubscribe = subscribe(
      getUserProfileRef(),
      (res) => {
        if (res.data) setProfileData(res.data);
      },
      (err) => console.error("Profile Error:", err),
    );
    return () => unsubscribe();
  }, [user, loading]);

  useEffect(() => {
    if (!debouncedSearch) {
      setSearchData(null);
      return;
    }
    
    // Subscribe to realtime full-text search results for emojis based on user input
    const unsubscribe = subscribe(
      searchEmojisRef({ query: debouncedSearch }),
      (res) => {
        if (res.data) setSearchData(res.data.emojis_search);
        setIsSearchLoading(false);
      },
      (err) => {
        console.error("Text Search Error:", err);
        setIsSearchLoading(false);
      },
    );

    return () => unsubscribe();
  }, [debouncedSearch]);

2. 使用者設定檔元件

app/profile/page.tsx

,更新掛鉤:

import { subscribe } from "@firebase/data-connect";
import { getUserProfileRef } from "@dataconnect/generated";

useEffect(() => {
  // Subscribe to realtime updates for the authenticated user's profile and stock ownership
  const unsubscribe = subscribe(
    getUserProfileRef(),
    (res) => {
      if (res.data) {
        setData(res.data);
      }
      setIsLoading(false);
    },
    (err) => {
      console.error("Profile Realtime Error:", err);
      setIsLoading(false);
    },
  );
  return () => unsubscribe();
}, []);

components/NavBar.tsx

 useEffect(() => {
    // Subscribe to realtime updates for the authenticated user's profile and stock ownership
    const unsub = subscribe(
      getUserProfileRef(),
      (res) => {
        if (res.data) setData(res.data);
      },
      (err) => console.error("Navbar Balance Realtime Error:", err),
    );
    return () => unsub();
  }, []);

如果是 components/FloatingMenu.tsx,請一併將手動 const { data } 物件替換為產生的 Hook:

const { data, refetch: refetchDashboard } = useGetDashboardData();

 useEffect(() => {
    if (!user) return;
    // Subscribe to realtime updates for the authenticated user's profile
    const unsub = subscribe(getUserProfileRef(), (res) => {
      if (res.data) {
        setProfileData(res.data);
        setOptimisticRole(null);
      }
    });
    return () => unsub();
  }, [user]);

重點回顧

  • getUserProfileRef / getDashboardDataRef系統會自動產生函式,準備執行 GraphQL 查詢,並保留資料表和檢視區塊定義的嚴格型別。
  • subscribeSQL Connect SDK 方法,用於監聽查詢。目前這個函式只會在元件掛接時擷取資料,但我們會在後續步驟中升級後端,在資料庫變更時自動觸發這個函式!
  1. 市場面板 (components/MarketPanel.tsx):同樣地,在 MarketPanel 元件 (components/MarketPanel.tsx) 中,您可以取代 TODO,同時呼叫多項查詢來建構側欄。
import { subscribe } from "@firebase/data-connect";
import { getDashboardDataRef, getEmojiSparklinesRef } from "@dataconnect/generated";

// Inside the MarketPanel component:
  useEffect(() => {
    // Subscribe to realtime updates for the main market dashboard data including top emojis and recent events
    const unsub = subscribe(
      getDashboardDataRef(),
      (res) => {
        if (res.data) setData(res.data);
      },
      (err) => console.error("Market Panel Realtime Error:", err)
    );
    return () => unsub();
  }, []);

  useEffect(() => {
    // Subscribe to realtime price history updates to render emoji sparkline charts
    const unsub = subscribe(
      getEmojiSparklinesRef(),
      (res) => {
        if (res.data?.emojiSparklines) {
          setSparklineRawData(res.data.emojiSparklines);
        }
      },
      (err) => console.error("Global Sparklines Error:", err)
    );
    return () => unsub();
  }, []);


  1. 排行榜頁面 (app/leaderboard/page.tsx)
import { subscribe } from "@firebase/data-connect";
import { getTopTradersRef } from "@dataconnect/generated";

// Inside the Leaderboard component:
  useEffect(() => {
    // Subscribe to realtime updates for the global leaderboard ranking top traders by net worth
    const unsubscribe = subscribe(
      getTopTradersRef(),
      (res) => {
        if (res.data) setData(res.data);
        setIsLoading(false);
      },
      (err) => {
        console.error("Leaderboard Realtime Error:", err);
        setIsLoading(false);
      },
    );
    return () => unsubscribe();
  }, []);

  1. 表情符號模式 (components/EmojiModal.tsx)
import { subscribe } from "@firebase/data-connect";
import {
  getEmojiHistoryStatsRef,
  getEmojiWhaleStatsRef,
} from "@dataconnect/generated";

// Inside the EmojiModal component:
  useEffect(() => {
    if (!emoji?.id) return;

    setStatsLoading(true);
    // Subscribe to realtime historical price and moving average statistics for the selected emoji
    const unsub = subscribe(
      getEmojiHistoryStatsRef({ emojiId: emoji.id }),
      (res) => {
        if (res.data) setStatsData(res.data);
        setStatsLoading(false);
      },
      (err) => {
        console.error("History Realtime Error:", err);
        setStatsLoading(false);
      },
    );
    return () => unsub();
  }, [emoji?.id]);

  useEffect(() => {
    // Subscribe to realtime whale statistics to identify the top shareholder for the selected emoji
    const unsub = subscribe(
      getEmojiWhaleStatsRef(),
      (res) => {
        if (res.data) setWhaleData(res.data);
      },
      (err) => console.error("Whale Realtime Error:", err),
    );
    return () => unsub();
  }, []);

實例觀摩

重新載入網頁應用程式,即可查看查詢的實際運作情形。首頁和側欄現在會顯示表情符號清單,直接從 PostgreSQL 資料庫擷取資料。

6. 處理使用者更新和市場交易

在本節中,您將使用 Firebase 驗證實作使用者登入功能,在 Firebase SQL Connect 中新增或更新使用者個人資料 (例如顯示名稱和實際位置)。您也會使用 SQL Connect 的 @transaction@check 指令,安全地執行原子多步驟市場事件。

導入使用者和位置連接器

開啟 dataconnect/friendly-exchange/mutations.gql。新增下列突變,以處理建立、更新及尋找使用者,藉此取代 TODO

# Upserts a user record using the Firebase Auth uid expression as the primary key
# Upsert (update or insert) a user's profile information
mutation UpsertUser($username: String!, $profileImage: String!)
@auth(level: USER) {
  user_upsert(
    data: {
      id_expr: "auth.uid"
      username: $username
      profileImage: $profileImage
    }
  )
}

# Update a user's role
mutation UpdateUserRole($role: String!) @auth(level: USER) {
  user_update(key: { id_expr: "auth.uid" }, data: { role: $role })
}

# Update a user's location
mutation UpdateUserLocation(
  $city: String!
  $latitude: Float!
  $longitude: Float!
) @auth(level: USER) {
  user_update(
    key: { id_expr: "auth.uid" }
    data: { city: $city, latitude: $latitude, longitude: $longitude }
  )
}

# Trigger a new market event for an emoji
mutation TriggerEvent(
  $emojiId: UUID!
  $impact: Float!
  $description: String!
  $now: Timestamp!
) @auth(level: USER) {
  event_insert(
    data: {
      userId_expr: "auth.uid"
      emojiId: $emojiId
      impact: $impact
      description: $description
      createdAt: $now
    }
  )
}

重點回顧

  • id_expr: "auth.uid"這會使用 auth.uid,由 Firebase 驗證權杖直接提供。透過在伺服器端評估這項作業,您可以確保使用者只能更新自己的設定檔資料,進而新增無法破解的安全防護層。

使用 @transaction 的鏈結邏輯

接下來,您要實作「造市者」,管理員可以觸發這個項目,模擬隨機市場活動。因為這需要同時更新表情符號的價格、記錄事件,以及更新系統的股票擁有權,所以我們需要原子交易。

將這項突變新增至 mutations.gql 檔案:

# Execute a market maker trade to adjust emoji price and shares
mutation MarketMakerTrade(
  $emojiId: UUID!
  $priceImpact: Float!
  $shareDelta: Int!
  $eventDesc: String!
  $newPrice: Float!
)
@auth(
  level: USER
  insecureReason: "This operation is safe to expose to any user."
)
@transaction {
  query @redact {
    user(key: { id_expr: "auth.uid" })
      @check(
        expr: "this != null && this.role == 'ADMIN'",
        message: "Access Denied: You must have the ADMIN role to deploy the Market Maker bot."
      ) {
      role
    }
  }
  stockOwnership_upsert(
    data: {
      userId: "system_market_maker"
      emojiId: $emojiId
      shares_update: { inc: $shareDelta }
    }
  )
  emoji_update(
    id: $emojiId
    data: { currentPrice_update: { inc: $priceImpact }, trend: $priceImpact }
  )
  event_insert(
    data: {
      userId: "system_market_maker"
      emojiId: $emojiId
      impact: $priceImpact
      description: $eventDesc
    }
  )
  priceHistory_insert(data: { emojiId: $emojiId, price: $newPrice })
}

重點回顧

  • @transaction確保所有資料庫作業 (插入/更新庫存、更新表情符號價格、記錄事件) 都能一起成功或一起失敗。
  • @check在繼續之前評估條件的指令。這裡會檢查已通過驗證的使用者 role 是否為 'ADMIN'。如果使用者只是標準 'USER',系統會拒絕整筆交易並回溯。
  • @redact防止查詢結果 (例如使用者的角色檢查) 回傳至回應酬載中的用戶端,確保交易回應乾淨無虞。

產生 SDK

由於您已在 GraphQL 檔案中定義新的突變,因此必須執行 SDK 產生器,TypeScript 前端才能呼叫該突變。

開啟終端機並執行:

firebase dataconnect:sdk:generate

在網頁應用程式中整合突變

在網頁應用程式中,您會將這些產生的 SDK 變異包裝在標準的非同步函式中,以處理錯誤擷取和 UI 通知。

開啟 lib/ExchangeService.tsx 並檢查包裝函式。將 TODO 區塊替換為下列實作項目:

import {
  upsertUser,
  updateUserLocation,
  marketMakerTrade,
  updateUserRole,
  triggerMarketCrash,
} from "@dataconnect/generated";

// Upsert (update or insert) a user's profile information and log the event
export const executeUpsertUser = async (
  username: string,
  profileImage: string,
  logEvent: (key: LogEventKey, params?: any) => void,
): Promise<void> => {
  logEvent("UPSERT_USER_MUTATION", { username });
  await upsertUser({ username, profileImage });
};

// Update a user's role and log the event
export const executeUpdateRole = async (
  role: string,
  logEvent: (key: LogEventKey, params?: any) => void
): Promise<void> => {
  logEvent("UPDATE_USER_ROLE_MUTATION", { role });
  await updateUserRole({ role });
};

// Update a user's city and geographic coordinates
export const executeUpdateLocation = async (
  city: string,
  latitude: number,
  longitude: number,
): Promise<void> => {
  await updateUserLocation({ city, latitude, longitude });
};

// Execute a random market maker trade and adjust an emoji's stock price
export const executeManualBotTrade = async (
  randomEmoji: any,
  username: string,
  logEvent: (key: LogEventKey, params?: any) => void,
): Promise<{ isBuy: boolean; tradeAmount: number }> => {
  logEvent("MARKET_MAKER_TRADE");
  const isBuy = Math.random() > 0.5;
  const tradeAmount = Number((Math.random() * (10 - 2) + 2).toFixed(2));

  await marketMakerTrade({
    emojiId: randomEmoji.id,
    priceImpact: isBuy ? tradeAmount : -tradeAmount,
    shareDelta: isBuy ? 10 : -10,
    eventDesc: `Admin ${username} triggered market event: ${randomEmoji.symbol} went ${isBuy ? "up" : "down"} by $${tradeAmount.toFixed(2)}.`,
    newPrice: Math.max(0.01, randomEmoji.currentPrice + (isBuy ? tradeAmount : -tradeAmount)),
  });

  return { isBuy, tradeAmount };
};

Triggering upsert on login: In app/src/components/Navbar.tsx, you can see how executeUpsertUser is called immediately after Firebase Authentication successfully signs a user in via Google Popup. This guarantees the SQL Connect database is synced with Firebase Auth.

See it in action

Now, click the Sign In button in the navbar. You can sign in using Firebase Authentication. After signing in:

  1. Navigate to your Profile and test out the Auto-Locate button. When you click Update Coordinates, the UpdateUserLocation mutation will execute.
  2. Open the Floating Control Panel (the purple icon in the bottom right corner).
  3. Click USER and switch your authorization level to ADMIN.
  4. Click Trigger random market activity. Because your role is now 'ADMIN', the @check directive passes, the @transaction executes, and you will instantly see the market prices update across your application!

7. Advanced operations with Native SQL

In this section, you will use Native SQL to execute complex Data Manipulation Language (DML) statements and leverage PostgreSQL-specific extensions.

While standard GraphQL and @views are ideal for strictly-typed CRUD and read-only operations, Native SQL provides execution-time flexibility. It allows you to use Common Table Expressions (CTEs) to chain multiple updates in a single database round-trip, and lets you query native PostgreSQL extensions directly.

Enable the PostGIS extension

Before we write geospatial queries, you need to enable the PostGIS extension on your Cloud SQL database.

  1. Navigate to the Google Cloud Console.
  2. Go to Cloud SQL -> select your provisioned instance -> click Cloud SQL Studio.
  3. Log into your database and execute the following command:
CREATE EXTENSION IF NOT EXISTS postgis;

Implement Native SQL Queries

Let's use Native SQL to find trending emojis near the user's physical location, and to calculate the top emojis per city using complex ranking.

  1. Open dataconnect/friendly-exchange/queries.gql.
  2. Add the following Native SQL queries using the _select field:
# Get top trending emojis partitioned by user city using native SQL
query GetTopEmojisByCity
@auth(
  level: PUBLIC
  insecureReason: "This operation is safe to expose to the public."
) {
  cityTrends: _select(
    sql: """
    WITH city_shares AS (
      SELECT
        u.city,
        AVG(u.latitude) as latitude,
        AVG(u.longitude) as longitude,
        e.id as emoji_id,
        e.symbol,
        e.name,
        SUM(so.shares) as total_shares,
        RANK() OVER (PARTITION BY u.city ORDER BY SUM(so.shares) DESC) as rank
      FROM stock_ownership so
      JOIN "user" u ON so.user_id = u.id
      JOIN emoji e ON so.emoji_id = e.id
      WHERE u.city IS NOT NULL AND u.latitude IS NOT NULL AND so.shares > 0
      GROUP BY u.city, e.id, e.symbol, e.name
    )
    SELECT city, latitude, longitude, emoji_id, symbol, name, total_shares
    FROM city_shares
    WHERE rank = 1
    ORDER BY city ASC
    """
    params: []
  )
}

# Get trending emojis within a geographic radius using native SQL and PostGIS extension
query GetTrendingEmojisNearMe(
  $userLng: Float!
  $userLat: Float!
  $radiusMeters: Float!
)
@auth(
  level: PUBLIC
  insecureReason: "This operation is safe to expose to the public."
) {
  regionalTrends: _select(
    sql: """
    SELECT
      e.id,
      e.symbol,
      e.name,
      e.current_price,
      e.trend,
      COUNT(so.shares)   AS regional_holders,
      SUM(so.shares)     AS regional_shares
    FROM emoji e
    JOIN stock_ownership so ON so.emoji_id = e.id
    JOIN "user" u            ON u.id = so.user_id
    WHERE u.latitude  IS NOT NULL
      AND u.longitude IS NOT NULL
      AND so.shares > 0
      AND ST_DWithin(
        ST_MakePoint(u.longitude, u.latitude)::geography,
        ST_MakePoint($1, $2)::geography,
        $3
      )
    GROUP BY e.id, e.symbol, e.name, e.current_price, e.trend
    ORDER BY regional_shares DESC
    LIMIT 10
    """
    params: [$userLng, $userLat, $radiusMeters]
  )
}

Key Takeaways

  • _select: Executes a Data Query Language (DQL) statement returning a JSON array ([Any]).
  • ST_DWithin: A native PostGIS function that calculates distances on a sphere. Native SQL allows you to use this without mapping complex geometry types into your GraphQL schema.
  • params: Variables like $userLng are bound to the SQL string via positional parameters ($1, $2, $3), preventing SQL injection.

Implement Native SQL Mutations

When a user buys or sells a stock, the system must validate their funds, deduct the cost, add the shares, update the global emoji price, and log the history. Doing this across multiple standard mutations could lead to race conditions. Instead, we can use a CTE (WITH) to do this atomically in one Native SQL execution.

Open dataconnect/friendly-exchange/mutations.gql and replace the TODOs with the following Native SQL mutations:

# Buy shares of an emoji stock
mutation BuyStock($emojiId: UUID!, $amount: Int!, $isDiscounted: Boolean!)
@auth(level: USER) {
  buyStock: _execute(
    sql: """
    WITH validated_params AS (
      SELECT
        $1::uuid AS emoji_id,
        $2::int AS amount,
        $3::boolean AS is_discounted,
        $4::text AS user_id
    ),
    target_emoji AS (
      SELECT
        e.id,
        (e.current_price * (CASE WHEN vp.is_discounted THEN 0.5 ELSE 1.0 END) * vp.amount) AS total_cost
      FROM emoji e
      CROSS JOIN validated_params vp
      WHERE e.id = vp.emoji_id
        AND vp.amount > 0
        AND vp.amount <= 100
    ),
    deduct_funds AS (
      UPDATE "user" u
      SET points = u.points - te.total_cost
      FROM target_emoji te, validated_params vp
      WHERE u.id = vp.user_id AND u.points >= te.total_cost
      RETURNING u.id
    ),
    upsert_ownership AS (
      INSERT INTO stock_ownership (user_id, emoji_id, shares)
      SELECT vp.user_id, vp.emoji_id, vp.amount
      FROM validated_params vp
      WHERE EXISTS (SELECT 1 FROM deduct_funds)
      ON CONFLICT (user_id, emoji_id) DO UPDATE
      SET shares = stock_ownership.shares + EXCLUDED.shares
      RETURNING stock_ownership.emoji_id
    ),
    update_emoji AS (
      UPDATE emoji e
      SET
        current_price = GREATEST(0.01, e.current_price + (e.current_price * 0.01 * vp.amount)),
        trend = GREATEST(0.01, e.current_price + (e.current_price * 0.01 * vp.amount)) - e.current_price
      FROM validated_params vp
      WHERE e.id = vp.emoji_id AND EXISTS (SELECT 1 FROM deduct_funds)
      RETURNING e.id, e.current_price, e.trend
    )
    INSERT INTO price_history (id, emoji_id, price, recorded_at)
    SELECT gen_random_uuid(), ue.id, ue.current_price, NOW()
    FROM update_emoji ue;
    """
    params: [$emojiId, $amount, $isDiscounted, { _expr: "auth.uid" }]
  )
}

# Sell shares of an emoji stock
mutation SellStock($emojiId: UUID!, $amount: Int!) @auth(level: USER) {
  sellStock: _execute(
    sql: """
    WITH validated_params AS (
      SELECT
        $1::uuid AS emoji_id,
        $2::int AS amount,
        $3::text AS user_id
    ),
    target_emoji AS (
      SELECT
        e.id,
        (e.current_price * vp.amount) AS total_revenue,
        GREATEST(0.01, e.current_price * POWER(0.99, vp.amount)) AS new_price
      FROM emoji e
      CROSS JOIN validated_params vp
      WHERE e.id = vp.emoji_id
        AND vp.amount > 0
        AND vp.amount <= 100
    ),
    check_shares AS (
      SELECT so.user_id
      FROM stock_ownership so
      CROSS JOIN validated_params vp
      WHERE so.user_id = vp.user_id
        AND so.emoji_id = vp.emoji_id
        AND so.shares >= vp.amount
    ),
    add_funds AS (
      UPDATE "user" u
      SET points = u.points + te.total_revenue
      FROM target_emoji te, validated_params vp
      WHERE u.id = vp.user_id AND EXISTS (SELECT 1 FROM check_shares)
      RETURNING u.id
    ),
    update_ownership AS (
      UPDATE stock_ownership so
      SET shares = so.shares - vp.amount
      FROM validated_params vp
      WHERE so.user_id = vp.user_id
        AND so.emoji_id = vp.emoji_id
        AND EXISTS (SELECT 1 FROM check_shares)
        AND EXISTS (SELECT 1 FROM add_funds)
    ),
    update_emoji AS (
      UPDATE emoji e
      SET
        current_price = te.new_price,
        trend = te.new_price - e.current_price
      FROM target_emoji te, validated_params vp
      WHERE e.id = vp.emoji_id
        AND EXISTS (SELECT 1 FROM check_shares)
        AND EXISTS (SELECT 1 FROM add_funds)
      RETURNING e.id, e.current_price, e.trend
    )
    INSERT INTO price_history (id, emoji_id, price, recorded_at)
    SELECT gen_random_uuid(), ue.id, ue.current_price, NOW()
    FROM update_emoji ue;
    """
    params: [$emojiId, $amount, { _expr: "auth.uid" }]
  )
}

Key Takeaways

  • _execute: Executes a Data Manipulation Language (DML) statement, such as UPDATE, INSERT, or DELETE.
  • Common Table Expressions (WITH): Each block in the CTE depends on the previous one. For example, add_funds will only execute if check_shares returns a result. This handles the complex conditions completely within Postgres.
  • Context Injection: { _expr: "auth.uid" } injects the authenticated user's ID into the query directly on the server, enforcing security.

Generate the SDK

Because you have defined new queries and mutations in your GraphQL files, you must run the SDK generator so your TypeScript frontend can call it.

Open your terminal and run:

firebase dataconnect:sdk:generate

Integrate Native SQL in the web app

  1. Native SQL returns a flexible JSON payload rather than a strictly typed object. Because of this, it's essential to manually validate the returned data shape in your client code to handle the dynamic response.
  2. Execute Trades: In lib/ExchangeService.tsx, we wrap the generated buyStock and sellStock SDKs. Notice how the return types buyResult and sellResult must be manually validated as arrays, because _execute returns dynamic JSON data based on your specific RETURNING clauses in the SQL strings.
  3. Replace the empty executeBuyStock and executeSellStock functions with your original complete code:
import { buyStock, sellStock, generateTradeHeadline, triggerEvent } from "@dataconnect/generated";
import { LogEventKey } from "./InspectorContext";

// Execute a stock purchase, validating limits and potentially generating an AI news headline for large trades
export const executeBuyStock = async (
  emoji: any,
  amount: number,
  isDiscounted: boolean,
  user: any,
  logEvent: (key: LogEventKey, params?: any) => void,
): Promise<void> => {
  const MAX_AMOUNT = 100;

  if (!Number.isInteger(amount) || amount <= 0 || amount > MAX_AMOUNT) {
    throw new Error(`Amount must be an integer between 1 and ${MAX_AMOUNT}.`);
  }
  const singleSharePrice = isDiscounted
    ? emoji.currentPrice * 0.5
    : emoji.currentPrice;
  const estimatedCost = singleSharePrice * amount;
  const estimatedImpact = emoji.currentPrice * 0.05 * amount;

  logEvent("BUY_STOCK_TRANSACTION", { amount, symbol: emoji.symbol });

  const response = await buyStock({
    emojiId: emoji.id,
    amount: amount,
    isDiscounted: isDiscounted,
  });

  const buyResult = response.data?.buyStock as any;

  if (
    !buyResult ||
    buyResult === 0 ||
    (Array.isArray(buyResult) && buyResult.length === 0)
  ) {
    throw new Error(
      "Transaction denied: Insufficient funds or price mismatch.",
    );
  }

  const actualCost = Array.isArray(buyResult)
    ? buyResult[0].actual_cost
    : estimatedCost;
  const actualImpact = Array.isArray(buyResult)
    ? buyResult[0].actual_impact
    : estimatedImpact;

// TODO: Optionally add a custom resolver to call AI to generate headline for this purchase
};

// Execute a stock sale, validating ownership and potentially generating an AI news headline for large trades
export const executeSellStock = async (
  emoji: any,
  amount: number,
  ownedShares: number,
  user: any,
  logEvent: (key: LogEventKey, params?: any) => void,
): Promise<void> => {
  const MAX_AMOUNT = 100;

  if (!Number.isInteger(amount) || amount <= 0 || amount > MAX_AMOUNT) {
    throw new Error(`Amount must be an integer between 1 and ${MAX_AMOUNT}.`);
  }
  if (amount > ownedShares) {
    throw new Error(
      "INSUFFICIENT SHARES: You cannot sell more shares than you own.",
    );
  }

  const estimatedRevenue = emoji.currentPrice * amount;
  const dropRatePerShare = 0.05;
  const targetPrice =
    emoji.currentPrice * Math.pow(1 - dropRatePerShare, amount);
  const estimatedImpact = Math.max(0.01, targetPrice) - emoji.currentPrice;

  logEvent("SELL_STOCK_TRANSACTION", { amount, symbol: emoji.symbol });

  const response = await sellStock({
    emojiId: emoji.id,
    amount: amount,
  });

  const sellResult = response.data?.sellStock as any;

  if (
    !sellResult ||
    sellResult === 0 ||
    (Array.isArray(sellResult) && sellResult.length === 0)
  ) {
    throw new Error("Transaction denied: Insufficient shares.");
  }

  const actualRevenue = Array.isArray(sellResult)
    ? sellResult[0].actual_revenue
    : estimatedRevenue;
  const actualImpact = Array.isArray(sellResult)
    ? sellResult[0].actual_impact
    : estimatedImpact;
// TODO: Optionally add a custom resolver to call AI to generate headline for this sale

};

Query Geospatial Data (Local Radar): In app/src/components/LocalRadar.tsx, we subscribe to the getTrendingEmojisNearMeRef query. The dynamic JSON array from the _select execution maps directly to the UI list, utilizing PostGIS's distance calculations.

import { subscribe } from "@firebase/data-connect";
import { getTrendingEmojisNearMeRef } from "@dataconnect/generated";

// ... inside the component
  useEffect(() => {
    if (!location) return;

    setIsLoadingTrends(true);

    // Subscribe to realtime updates for trending emojis within a 50km radius
    const unsub = subscribe(
      getTrendingEmojisNearMeRef({
        userLat: location.lat,
        userLng: location.lng,
        radiusMeters: 50000, // 50km
      }),
      (res) => {
        if (res.data) setLocalData(res.data);
        setIsLoadingTrends(false);
      },
      (err) => {
        console.error("Local Radar Realtime Error:", err);
        setIsLoadingTrends(false);
      },
    );

    return () => unsub();
  }, [location?.lat, location?.lng]);

Query Geospatial Data (Global Assets Map): In app/src/app/map/page.tsx (the Insights Page), we use Native SQL's complex window functions (RANK() OVER) to find the single most popular emoji for every city in the database.

import { subscribe } from "@firebase/data-connect";
import { getTopEmojisByCityRef, getTrendingEmojisNearMeRef, getUserProfileRef } from "@dataconnect/generated";

// ... inside the component
  useEffect(() => {
    // Subscribe to realtime updates for the authenticated user's profile and stock ownership
    const unsub = subscribe(getUserProfileRef(), (res) => {
      if (res.data) setProfileData(res.data);
    });
    return () => unsub();
  }, []);

  useEffect(() => {
    // Subscribe to realtime updates for top trending emojis partitioned by user city
    const unsub = subscribe(getTopEmojisByCityRef(), (res) => {
      if (res.data) setCityData(res.data);
    });
    return () => unsub();
  }, []);

  useEffect(() => {
    setRadarLoading(true);
    // Subscribe to realtime updates for trending emojis within a specified geographic radius
    const unsub = subscribe(
      getTrendingEmojisNearMeRef({
        userLat: coords.lat,
        userLng: coords.lng,
        radiusMeters: radiusKm * 1000,
      }),
      (res) => {
        if (res.data) setRadarData(res.data);
        setRadarLoading(false);
      },
    );
    return () => unsub();
  }, [coords.lat, coords.lng, radiusKm]);

See it in action

  1. In your browser, navigate to the Geo page from the top navigation bar.
  2. If your location is correctly set in your Profile, the Global Top Assets map will ping the GetTopEmojisByCity native query to drop pins on cities with high trade volumes.
  3. Click Scan Local Network. The Local Radar Scanner will ask for your browser's location and ping the GetTrendingEmojisNearMe native query, utilizing PostGIS to find the top assets specifically traded within 50km of your coordinates!
  4. Navigate to the Home page or Profile page and purchase some assets to see your balance deduct and the emoji price update automatically via your atomic _execute queries.

8. Realtime subscriptions and caching

In the previous section, we used the subscribe() method in our React components to fetch data. While that successfully retrieved the initial state, a true stock exchange needs to feel alive. If another user buys a massive amount of emoji stock, your screen should update instantly.

This is where Firebase SQL Connect's Realtime features come in.

What is Realtime and how does it work?

Realtime support allows your application to receive proactive notifications from the server whenever data your app is using has been updated.

Here is the underlying mechanism:

  1. Trigger (@refresh): You tell the SQL Connect backend which specific mutations should trigger a data refresh for a given query.
  2. Broadcast: When one of those mutations executes (e.g., someone runs BuyStock), the server proactively broadcasts a realtime notification to any connected clients listening to that query.
  3. Cache Update: When the notification arrives, the JS SDK treats it just like an ad-hoc query execution. The local cache is instantly updated with the new data.
  4. UI Reactivity: The SDK automatically fires the onNext callbacks for all active subscribers, causing your React state to update and your UI to re-render "in real time".

Add @refresh triggers to your queries

To enable this on the backend, we need to add the @refresh directive to our queries.

  1. Open dataconnect/friendly-exchange/queries.gql.
  2. Update your existing queries by attaching @refresh directives for every market-altering mutation. For example, update GetDashboardData and GetUserProfile:
# Get dashboard data including top emojis by price and recent market events
query GetDashboardData
@auth(
  level: PUBLIC
  insecureReason: "This operation is safe to expose to the public."
)
@refresh(onMutationExecuted: { operation: "BuyStock" })
@refresh(onMutationExecuted: { operation: "SellStock" })
@refresh(onMutationExecuted: { operation: "TriggerEvent" })
@refresh(onMutationExecuted: { operation: "MarketMakerTrade" }) {
  emojis(orderBy: [{ currentPrice: DESC }]) {
    id
    symbol
    name
    description
    currentPrice
    trend
  }
  events(orderBy: [{ createdAt: DESC }], limit: 15) {
    id
    description
    impact
    createdAt
    user {
      username
      profileImage
    }
    emoji {
      symbol
    }
  }
}

# Get current authenticated user profile and their stock ownership using auth.uid
query GetUserProfile
@auth(level: USER)
@refresh(onMutationExecuted: { operation: "BuyStock" })
@refresh(onMutationExecuted: { operation: "SellStock" })
@refresh(onMutationExecuted: { operation: "UpdateUserLocation" })
@refresh(onMutationExecuted: { operation: "UpdateUserRole" }) {
  user(id_expr: "auth.uid") {
    points
    username
    profileImage
    role
    stockOwnerships_on_user {
      shares
      emoji {
        id
        symbol
        currentPrice
        name
      }
    }
    city
    latitude
    longitude
  }
}

Key Takeaways

  • @refresh(onMutationExecuted: ...): Instructs the server to re-evaluate this query and push new data to subscribers whenever the specified mutation occurs.

Generate the SDK

Because you have defined new queries and mutations in your GraphQL files, you must run the SDK generator so your TypeScript frontend can call it.

Open your terminal and run:

firebase dataconnect:sdk:generate

Handle Realtime Subscriptions in the Web App

We already laid the groundwork for this in the previous section by using the subscribe method. Let's look closer at how the generated SDK handles this in React.

If you open app/src/app/page.tsx (the Home page), you will see the useEffect hook managing the dashboard data:

import { subscribe } from "@firebase/data-connect";
import { getDashboardDataRef } from "@dataconnect/generated";

// ... inside the component
  useEffect(() => {
    const queryRef = getDashboardDataRef();

    // The subscribe function registers the QueryRef and callbacks
    const unsubscribe = subscribe(
      queryRef,
      (res) => {
        // onNext: Fires initially, AND whenever a @refresh trigger occurs
        if (res.data) setDashboardData(res.data);
        setIsDashboardLoading(false);
      },
      (err) => {
        // onError: Handles any server or permission errors
        console.error("Dashboard Realtime Error:", err);
        setIsDashboardLoading(false);
      }
    );

    // onComplete/Cleanup: Unregisters the callbacks when the component unmounts
    return () => unsubscribe();
  }, [user]);

Key Takeaways

  • subscribe(queryRef, onNext, onError): Enables Realtime notifications for the specific QueryRef.
  • unsubscribe(): Calling subscribe returns a cleanup function. It is critical to return this in your useEffect so that when the component unmounts (e.g., the user navigates away), the subscription is canceled and memory leaks are prevented.
  • Caching Efficiency: If multiple components subscribe to the same query (like GetDashboardData), the SDK shares the cached result. When a Realtime notification arrives, the cache updates once, and all active subscribers are notified automatically.

See it in action

Because you've added @refresh to your backend and subscribe to your frontend, your app is now fully reactive.

  1. Open your web app in two separate browser windows side-by-side.
  2. In one window, purchase a few shares of an emoji.
  3. Watch the second window—without refreshing the page, you will instantly see the emoji's price increase!

9. Conclusion

Congratulations, you've successfully built and deployed a realtime, highly complex trading platform directly on top of PostgreSQL using Firebase SQL Connect!

By utilizing SQL Connect, you were able to:

  • Define a strictly-typed GraphQL schema that maps directly to PostgreSQL.
  • Enforce granular, row-level security using Firebase Authentication and @auth directives.
  • Leverage advanced Native SQL to query geospatial data with PostGIS and write atomic market transactions via CTEs.
  • Make your entire application reactive using the @refresh directive for realtime subscriptions.
  • Seamlessly generate frontend SDKs to keep your client code synced with your database.

If you want to play with your own market data, feel free to insert your own mock emojis, locations, and pricing histories using the Firebase SQL Connect extension by mimicking the .gql seed files, or add them through the SQL Connect execution pane in VS Code.

10. Deploy to Cloud

Now that you've worked through the local development iteration, it's time to deploy your schema, data, and queries to the server. This can be done using the Firebase SQL Connect VS Code extension or the Firebase CLI.

Set up Firebase Authentication in your Firebase project

  1. Set up Firebase Authentication with Google Sign-In.
  2. (Optional) Allow domains for Firebase Authentication using the Firebase console (for example, http://127.0.0.1).
    1. In the Authentication settings, go to Authorized Domains.
    2. Click "Add Domain" and include your local domain in the list.

Enable required PostgreSQL Extensions

Because this app utilizes PostgreSQL extensions for vector search and location tracking, you must manually enable them on your provisioned Cloud SQL instance before deploying your schema.

  1. Navigate to the Google Cloud Console.
  2. Go to Cloud SQL -> select your provisioned instance -> click Cloud SQL Studio.
  3. Log into your database and execute the following commands:
# Required for the Geo Map page
CREATE EXTENSION IF NOT EXISTS postgis;
# Required for Vector Search
CREATE EXTENSION IF NOT EXISTS "vector";
# Required for automatic Vector Search embedding generation
CREATE EXTENSION IF NOT EXISTS "google_ml_integration";

Build your web app for hosting

Back in VS Code, ensure you have placed your firebaseConfig variables in lib/firebase.tsx (as done in the setup section).

Next, guarantee that your frontend is using the latest generated hooks by running:

firebase dataconnect:sdk:generate

Then, build the React web app for hosting deployment:

npm run build

Deploy with the Firebase CLI

In dataconnect/dataconnect.yaml, ensure that your instance ID, database, and service ID match your actual Google Cloud project identifiers, and use the v1 specification:

specVersion: v1
serviceId: your-project-id-service
location: us-west4
schemas:
  - source: ./schema
    datasource:
      postgresql:
        database: your-project-id-database
        cloudSql:
          instanceId: your-project-id-instance
connectorDirs:
  - ./friendly-exchange

In your terminal, run the following command to deploy:

firebase deploy --only dataconnect,hosting

For updates or refactors, run this command to compare your schema changes:

firebase dataconnect:sql:diff

If the changes are acceptable, apply them with:

firebase dataconnect:sql:migrate

Your Cloud SQL for PostgreSQL instance will be updated with the final deployed schema and data. You should now be able to see your app live at your-project.web.app/.

Learn more

11. Optional: Vector search with Firebase SQL Connect (billing required)

In this section, you'll enable vector search in your emoji exchange using Firebase SQL Connect. This feature allows for semantic, content-based searches, such as finding emojis that match a vibe or concept using vector embeddings.

This step requires that you completed the last step of this codelab to deploy to Google Cloud.

Update the schema to include embeddings for a field

In dataconnect/schema/schema.gql, add the descriptionEmbedding field to your Emoji table. Replace your existing Emoji type with this updated version:

# Emojis
# emoji-stockOwnership is a one-to-many relationship, emoji-priceHistory is a one-to-many relationship
# Implements @searchable directives for full-text search
# Optional: implements Vector type for semantic search
type Emoji @table {
  id: UUID! @default(expr: "uuidV4()")
  symbol: String!
  name: String! @searchable
  tags: [String!]
  description: String! @searchable
  descriptionEmbedding: Vector @col(size: 768)
  currentPrice: Float! @default(value: 10.0)
  trend: Float! @default(value: 0.0)
}

Key Takeaways

  • descriptionEmbedding: Vector @col(size: 768): This field stores the semantic embeddings of your emoji descriptions, enabling vector-based content search in your app.

Add a vector search query

In dataconnect/friendly-exchange/queries.gql, add the following query to perform vector searches:

# Search emoji descriptions using Vertex AI embeddings
query VectorSearchEmojis($query: String!)
@auth(
  level: PUBLIC
  insecureReason: "This operation is safe to expose to the public."
)
@refresh(onMutationExecuted: { operation: "BuyStock" })
@refresh(onMutationExecuted: { operation: "SellStock" })
@refresh(onMutationExecuted: { operation: "TriggerEvent" })
@refresh(onMutationExecuted: { operation: "MarketMakerTrade" }) {
  emojis_descriptionEmbedding_similarity(
    compare_embed: { model: "text-multilingual-embedding-002", text: $query }
    method: COSINE
    within: 2
    limit: 15
  ) {
    id
    symbol
    name
    description
    currentPrice
    trend
    _metadata {
      distance
    }
  }
}

Key Takeaways:

  • compare_embed: Specifies the embedding model (text-multilingual-embedding-002) and the input text ($query) for comparison.
  • method: Specifies the similarity method (COSINE), measuring the cosine similarity between the vectors.
  • within: Limits the search to emojis with a distance of 2 or less, focusing on close content matches.

Generate the SDK

Because you have defined new queries and mutations in your GraphQL files, you must run the SDK generator so your TypeScript frontend can call it.

Open your terminal and run:

firebase dataconnect:sdk:generate

Activate Vertex AI and re-deploy

  1. Follow the prerequisites guide to set up Vertex AI APIs from Google Cloud. This step is essential to support the embedding generation.
  2. Re-deploy your schema to activate pgvector and vector search by running firebase deploy --only dataconnect or clicking "Deploy to Production" using the Firebase SQL Connect VS Code extension.

Populate the database with embeddings

  1. Open the dataconnect folder in VS Code.
  2. Click Run (Production) in optional_vector_seed.gql to populate your deployed database with the 768-dimensional embeddings for the emojis.

Implement the vector search function in your app

Now that the schema and query are set up, integrate the vector search into your app's frontend.

In app/src/app/page.tsx (your Home component), review the useEffect that listens to the search input and swaps dynamically between full-text search and vector search based on the user's selected searchMode:

import { subscribe } from "@firebase/data-connect";
import {
  getDashboardDataRef,
  searchEmojisRef,
  vectorSearchEmojisRef, // <-- Add this!
  getChronologicalTickerRef,
  getUserProfileRef,
} from "@dataconnect/generated";

// Inside Home component, find the search useeffect
useEffect(() => {
    if (!debouncedSearch) {
      setSearchData(null);
      return;
    }

    let unsubscribe: () => void;

    if (searchMode === "TEXT") {
      // Subscribe to realtime full-text search results for emojis based on user input
      unsubscribe = subscribe(
        searchEmojisRef({ query: debouncedSearch }),
        (res) => {
          if (res.data) setSearchData(res.data.emojis_search);
          setIsSearchLoading(false);
        },
        (err) => {
          console.error("Text Search Error:", err);
          setIsSearchLoading(false);
        },
      );
    } else {
      // Subscribe to realtime vector search results using semantic similarity for emojis based on user input
      unsubscribe = subscribe(
        vectorSearchEmojisRef({ query: debouncedSearch }),
        (res) => {
          if (res.data)
            setSearchData(res.data.emojis_descriptionEmbedding_similarity);
          setIsSearchLoading(false);
        },
        (err) => {
          console.error("Vector Search Error:", err);
          setIsSearchLoading(false);
        },
      );
    }

    return () => {
      if (unsubscribe) unsubscribe();
    };
  }, [debouncedSearch, searchMode]);

See it in action

Navigate to the search bar on your app's homepage. Type in abstract phrases like "happy", "nature", or "technology". Toggle the search mode from TEXT to VECTOR and notice how the results shift from exact string matches to contextual, semantic matches returned directly from Vertex AI and PostgreSQL!

12. Optional: Custom Resolvers with Vertex AI (billing required)

10:00

By writing Custom Resolvers, you can extend Firebase SQL Connect to support other data sources and combine them into your unified GraphQL schema. In this section, you'll write a Firebase Cloud Function that uses Vertex AI (Gemini) to generate a satirical financial news headline whenever a user makes a large trade, and expose that function through SQL Connect.

Initialize the custom resolver

Instead of creating all the boilerplate files manually, the Firebase CLI has a built-in generator for custom resolvers.

Open your terminal in the root of your project and run:

firebase init dataconnect:resolver

When prompted by the CLI:

  1. Enter generateTradeHeadline as the name for your custom resolver.
  2. Select TypeScript to generate the example implementation.

The CLI will automatically create a new dataconnect/schema_generateTradeHeadline/schema.gql file, initialize a functions directory with sample code, and link the resolver in your dataconnect.yaml configuration!

Define the custom resolver schema

Next, you need to define the exact shape of your custom endpoint using a GraphQL schema.

Open the newly generated dataconnect/schema_generateTradeHeadline/schema.gql file and replace its contents with the following code:

# Custom resolver fields can be defined on root Query and Mutation types.
type Mutation {
  # This field will be backed by your Cloud Function.
  generateTradeHeadline(
    emojiSymbol: String!
    emojiName: String!
    username: String!
    tradeAmount: Int!
    tradeCost: Float!
    tradeType: String!
  ): String!
}

Key Takeaways:

  • By placing this inside the root type Mutation, you are telling SQL Connect that this operation might have side-effects (like calling an AI API) rather than just reading data.

Implement the custom resolver logic

Next, implement your resolver using Cloud Functions. Under the hood, you are creating a GraphQL server; however, Cloud Functions provides a helper method, onGraphRequest, that handles the boilerplate so you only need to write the core logic.

Open your Firebase Functions file (functions/src/index.ts), which the CLI generated for you. Replace the entire file with the Gemini API implementation:

import { setGlobalOptions } from "firebase-functions";
import {
  FirebaseContext,
  onGraphRequest,
} from "firebase-functions/dataconnect/graphql";
import { initializeApp, getApps } from "firebase-admin/app";
import { GoogleGenAI } from "@google/genai";

setGlobalOptions({
  maxInstances: 10,
  region: "us-west4",
});

if (getApps().length === 0) {
  initializeApp();
}

const ai = new GoogleGenAI({
  vertexai: true,
  project: process.env.GCLOUD_PROJECT || "your-project-id",
  location: process.env.GCLOUD_LOCATION || "us-west4",
});

const headlineOpts = {
  // Points to the schema you defined earlier
  schemaFilePath: "dataconnect/schema_generateTradeHeadline/schema.gql",
  resolvers: {
    mutation: {
      // Generate a satirical financial news headline for a stock trade using Vertex AI
      async generateTradeHeadline(
        _parent: unknown,
        args: Record<string, unknown>,
        _contextValue: FirebaseContext,
        _info: unknown,
      ): Promise<string> {
        const {
          emojiSymbol,
          emojiName,
          username,
          tradeAmount,
          tradeCost,
          tradeType,
        } = args;

        try {
          const prompt = `You are a hype-driven, satirical financial news bot. 
          A user named '${username}' just executed a massive ${tradeType} of ${tradeAmount} shares of ${emojiSymbol} (${emojiName}) for $${tradeCost}. 
          Write a single, punchy, dramatic news headline (under 12 words) about this market move, use puns wherever possible, but don't round or exagerate the numbers. Include the asset symbol.`;
          
          const response = await ai.models.generateContent({
            model: "gemini-2.5-flash-lite",
            contents: prompt,
          });

          if (!response.text) {
            throw new Error("No text returned from Vertex AI");
          }

          return response.text.trim();
        } catch (error) {
          console.error("Vertex AI generation failed:", error);
          return `BREAKING: Massive ${tradeType} detected on ${emojiSymbol}! Market reacting.`;
        }
      },
    },
  },
};

export const generateTradeHeadline = onGraphRequest(headlineOpts);

重點回顧:

  • onGraphRequest:專用的 Firebase 函式 包裝函式,可將 Cloud 函式 對應至 SQL Connect Custom Resolver 結構定義。
  • args:從 GraphQL 異動傳遞的引數會自動在此輸入及擷取,並插入 Gemini 提示詞。

將突變新增至連接器

自訂解析器邏輯現已存在,請透過應用程式的連接器公開,以便前端呼叫。

開啟 dataconnect/friendly-exchange/mutations.gql 並新增突變:

# Generate an AI headline for a stock trade
mutation GenerateTradeHeadline(
  $emojiSymbol: String!
  $emojiName: String!
  $username: String!
  $tradeAmount: Int!
  $tradeCost: Float!
  $tradeType: String!
)
@auth(
  level: USER
  insecureReason: "This operation is safe to expose to any authenticated user."
) {
  aiHeadline: generateTradeHeadline(
    emojiSymbol: $emojiSymbol
    emojiName: $emojiName
    username: $username
    tradeAmount: $tradeAmount
    tradeCost: $tradeCost
    tradeType: $tradeType
  )
}

部署及產生 SDK

由於自訂解析器是透過 Cloud Functions 執行,您必須將函式部署至 Google Cloud,端點才會啟用。

開啟終端機並部署函式:

firebase deploy --only functions

部署完成後,請產生前端 SDK,納入新的 AI 突變:

firebase dataconnect:sdk:generate

在網頁應用程式中整合 AI Resolver

讓我們設定這項功能,只要交易 10 股以上的股票,就會觸發即時新聞快訊!

開啟 lib/ExchangeService.tsx。首先,請務必在頂端匯入 generateTradeHeadlinetriggerEvent

import { 
  buyStock, 
  sellStock, 
  generateTradeHeadline, 
  triggerEvent 
} from "@dataconnect/generated";

接著,向下捲動至 executeBuyStock 函式底部,並在函式結束前,將 TODO 替換為 AI 觸發區塊:

// ... (existing executeBuyStock code)

  const actualImpact = Array.isArray(buyResult)
    ? buyResult[0].actual_impact
    : estimatedImpact;

  if (amount >= 10 && user) {
    setTimeout(() => {
      logEvent("GENERATE_HEADLINE_RESOLVER");
    }, 2000);

    const headlineResult = await generateTradeHeadline({
      emojiSymbol: emoji.symbol,
      emojiName: emoji.name,
      username: user.displayName || "Anonymous Whale",
      tradeAmount: amount,
      tradeCost: actualCost.toFixed(2),
      tradeType: "BUY",
    });

    await triggerEvent({
      emojiId: emoji.id,
      impact: actualImpact.toFixed(2),
      description: `GEMINI REPORT: ${headlineResult.data?.aiHeadline}`,
      now: new Date().toISOString(),
    });
  }
};

executeSellStock 函式的底部執行完全相同的操作:

// ... (existing executeSellStock code)

  const actualImpact = Array.isArray(sellResult)
    ? sellResult[0].actual_impact
    : estimatedImpact;

  if (amount >= 10 && user) {
    const headlineResult = await generateTradeHeadline({
      emojiSymbol: emoji.symbol,
      emojiName: emoji.name,
      username: user.displayName || "Anonymous Whale",
      tradeAmount: amount,
      tradeCost: actualRevenue.toFixed(2),
      tradeType: "SELL",
    });

    await triggerEvent({
      emojiId: emoji.id,
      impact: actualImpact.toFixed(2),
      description: `GEMINI REPORT: ${headlineResult.data?.aiHeadline}`,
      now: new Date().toISOString(),
    });
  }
};

實例觀摩

  1. 重新載入網頁應用程式。
  2. 確認你已登入帳戶,且帳戶餘額充足。
  3. 選取表情符號,並一次購買10 個以上的分享
  4. 查看資訊主頁右側的全球市場行情表。幾秒鐘後,你就會看到 Gemini 生成的自訂諷刺新聞標題!