C.2 模組

在 GRT 中,模組是包含一組函式的程式庫,這些函式會匯出以供其他模組、指令碼或 Workbench 本身中的程式碼使用。模組可以使用 C++ 或 Python 撰寫,但是用於引數和傳回值的資料類型必須是 GRT 類型。

GRT 模組類似於 Python 模組,但是它們是從內建的 grt 模組匯入,而不是直接從外部檔案匯入。grt 模組中載入的模組清單是從 grt.modules 取得。模組可以在 Python 中使用像是 from grt.modules import WbModel 之類的陳述式匯入。

若要將函式從 Python 程式碼匯出為模組,請執行下列步驟

  1. 原始程式檔必須位於使用者模組資料夾中。此路徑會顯示在 Workbench 指令碼 Shell 中,標籤為 正在尋找使用者外掛程式於。也可以使用主選單項目 指令碼安裝外掛程式/模組檔案 來安裝檔案。

    表 C.2 預設使用者模組檔案位置

    作業系統 檔案路徑
    Windows %AppData%\MySQL\Workbench\modules
    macOS ~username/Library/Application Support/MySQL/Workbench/modules
    Linux ~username/.mysql/workbench/modules

  2. 原始程式檔名必須具有 _grt.py 副檔名;例如,my_module_grt.py

  3. 必須定義一些模組中繼資料。可以使用 wb 模組中的 DefineModule 函式來完成此操作

    from wb import *
    ModuleInfo = DefineModule(name='MyModule', author='Your Name', version='1.0')
  4. 要匯出的函式需要宣告其簽章。這是使用先前建立的 ModuleInfo 物件中的 export 裝飾器來實現的

    @ModuleInfo.export(grt.INT, grt.STRING)
    def checkString(s):
       ...

    對於 export 陳述式,傳回類型會先列出,接著是輸入參數類型,以 GRT 類型名稱指定。可以使用下列類型名稱

    • grt.INT:整數值。也用於布林值。

    • grt.DOUBLE:浮點數值。

    • grt.STRING:UTF-8 或 ASCII 字串資料。

    • grt.DICT:鍵值字典項目。鍵必須是字串。

    • grt.LIST:其他值的清單。可以將內容的類型指定為形式為 (grt.LIST, <type-or-class>) 的元組。例如,(grt.LIST, grt.STRING) 表示字串清單。對於資料表物件清單,將指定以下內容:(grt.LIST, grt.classes.db_table)

    • grt.OBJECT:GRT 物件或 GRT 類別物件的執行個體,來自 grt.classes

    注意

    這些類型定義在 grt 模組中,必須先匯入該模組才能使用這些類型。

以下程式碼片段說明如何宣告匯出單一函式的模組

from wb import *
import grt

ModuleInfo = DefineModule(name='MyModule', author="your name", version='1.0')

@ModuleInfo.export(grt.DOUBLE, grt.STRING, (grt.LIST, grt.DOUBLE))
def printListSum(message, doubleList):
   sum = 0
   for d in doubleList:
      sum = sum + d
   print message, sum
   return sum