SODA for In-Database JavaScriptの開始

SODA for In-Database JavaScriptにアクセスする方法、およびこれを使用してデータベース・コレクションを作成し、ドキュメントをコレクションに挿入し、コレクションからドキュメントを取得する方法について説明します。

SODA for MLE JavaScriptの使用を開始する前に、コレクションの格納に使用されるアカウント(この場合はemily)に、直接またはDB_DEVELOPER_ROLEを使用してSODA_APPロールを付与する必要があります:

grant soda_app to emily
SODA機能にアクセスするには、MLE JavaScript SQLドライバを使用する必要があります。コードが起動される時点ではデータベース・セッションが存在するため、追加の接続処理は不要です。例8-1では、次の方法を示します:
  • SODAコレクションの作成、

  • JSONドキュメントの挿入、および

  • コレクション内のすべてのSODAドキュメントに対する反復と、画面へのその内容の出力

例8-1で示す各概念(コレクションの作成、ドキュメントの追加と変更、およびコレクションの削除)については、この章の後半で詳しく説明します。

例8-1 MLE JavaScriptでのSODAの一般的なワークフロー

この例では、MLE JavaScriptでSODAコレクションを使用する一般的なワークフローを示します。この例では、MLEモジュールを使用するかわりに、インライン・コール仕様を実装することでプロセスを簡素化します。

CREATE OR REPLACE PROCEDURE intro_soda(
    "dropCollection" BOOLEAN
) AUTHID CURRENT_USER
AS MLE LANGUAGE JAVASCRIPT
{{
    
  // use the soda object, available in the global scope instead of importing
  // the mle-js-oracledb driver, getting the default connection and extracting
  // the SodaDatabase from it
  const col = soda.createCollection("MyCollection");

  // create a JSON document (based on the HR.EMPLOYEES table for the employee with id 100)
  const doc = {
    "_id" : 100,
    "job_id" : "AD_PRES",
    "last_name" : "King",
    "first_name" : "Steven",
    "email" : "SKING",
    "manager_id" : null,
    "department_id" : 90
  };

  // insert the document into collection
  col.insertOne(doc);

  // find all documents in the collection and print them on screen
  // use a cursor to iterate over all documents in the collection
  const c = col.find()
            .getCursor();

  let resultDoc;
  
  while (resultDoc = c.getNext()){
    const content = resultDoc.getContent();
    console.log(`
      ------------------------------------------
      key:           ${resultDoc.key}
      content (select fields):
      - _id:         ${content._id}
      - job_id:      ${content.job_id}
      - name:        ${content.first_name} ${content.last_name}
      version:       ${resultDoc.version}
      media type:    ${resultDoc.mediaType}`
    );
  }

  // it is very important to close the SODADocumentCursor to free resources
  c.close();

  // optionally drop the collection
  if (dropCollection){
    // there is no auto-commit, the outstanding transaction must be
    // finished before the collection can be dropped
    session.commit();
    col.drop();
  }
}};
/

コードを試すには、お気に入りのIDEを使用してプロシージャを実行します。次に、intro_sodaプロシージャのコール結果の例を示します:

BEGIN
  intro_soda(true);
END;
/

結果:

------------------------------------------
key:           03C202
content (select fields):
- _id:         100
- job_id:      AD_PRES
- name:        Steven King
version:       17EF0F3C102653DDE063DA464664399C
media type:    application/json

PL/SQL procedure successfully completed.