はじめに
Oracle Database 23c Free - Developer Releaseで、JSON Schemaを試してみました。
本記事の前提条件
- こちらを参考に、23cをインストールしてあること
実際に試してみた
- まずはJSON Schemaを試すのに使うユーザーを作成します。
-
oracleユーザーから、systemユーザーにログインします。
[oracle@db23cfree ~]$ sqlplus system/password@freepdb1
-
検証用のユーザーを作成します。
SQL> CREATE USER jsonschema_test IDENTIFIED BY "password";
-
権限を付与します。
SQL> GRANT CREATE TABLE, CREATE DOMAIN UNLIMITED TABLESPACE TO jsonschema_test;
-
jsonschema_testユーザーでログインします。
[oracle@db23cfree ~]$ sqlplus jsonschema_test/password@freepdb1
-
ドメインを使用してJSONスキーマを定義します。JSONドキュメントの構造と型を定義できます。
SQL> create domain product_schema as JSON validate using '{ "type": "object", "additionalProperties":false, "required":["starring"], "properties": { "id": {"type": "number"} , "type" : {"type":"string","maxLength": 50}, "title" : {"type":"string","maxLength": 50}, "format" : {"type":"string","maxLength": 50}, "condition" : {"type":"string","maxLength": 50}, "price": {"type": "number"}, "comment" : {"type":"string","maxLength": 50}, "starring" : {"type":"array"}, "year": {"type": "number"} , "decade" : {"type":"string","maxLength": 50} } }';
starringの配列が存在しない場合、新しいデータを挿入しようとするとエラーが発生します。また、 AdditionalPropertiesフィールドも定義してあります。これにより、JSONへの新しいフィールドの入力が許可されなくなります。
-
スキーマを定義したら、新しい表を作成します。
SQL> CREATE TABLE products(json_data JSON DOMAIN product_schema);
-
最初のinsertを試します。これはスキーマの構造に従っているので、エラーは発生しません。
SQL> insert into products(json_data) values( '{ "id": 100, "type": "movie", "title": "Coming to America", "format": "DVD", "condition": "acceptable", "price": 5, "comment": "DVD in excellent condition, cover is blurred", "starring": [ "Eddie Murphy", "Arsenio Hall", "James Earl Jones", "John Amos" ], "year": 1988, "decade": "80s" } '); commit;
-
次のJSONドキュメントには、starringのフィールドがありません。よって、エラーが発生します。
SQL> insert into products(json_data) values( '{ "id": 100, "type": "movie", "title": "Coming to America", "format": "DVD", "condition": "acceptable", "price": 5, "comment": "DVD in excellent condition, cover is blurred", "year": 1988, "decade": "80s" } '); insert into products(json_data) values( * ERROR at line 1: ORA-40875: JSON schema validation error
-
また、pages という新しいフィールドを追加しましたが、この場合でもエラーが発生します。
SQL> insert into Products(json_data) values( '{ "id": 103, "pages": 250, "title": "The Thing", "type": "book", "condition": "okay", "price": 2.5, "author": "Alan Dean Forster", "starring": [ "Eddie Murphy", "Arsenio Hall", "James Earl Jones", "John Amos" ], "year": 1982, "decade": "80s" } '); insert into Products(json_data) values( * ERROR at line 1: ORA-40875: JSON schema validation error