Pact的文档说,您可以使用模式键入对象。我一直想不出该怎么做。
当创建一个对象时,例如在REPL中,例如{"a":1.0,"b":2.0}
,它的类型是object:*
。
我有一个架构:
(defschema data
a : decimal
b : decimal
)
还有一个使用这个的表模式:
(defschema table-schema
v : {data}
)
(deftable my-table:{table-schema})
注意:上面没有类型检查(见下面的REPL输出(
我找不到插入此表的方法,因为它会产生类型错误:Type error: expected (defschema data [a:decimal, b:<a>]), found object:* at : (insert (deftable my-table:(defschema table-schema [v:(de... "123" {"v": {"value": 100.0,"rate": 0.5}}
非常感谢。
完整代码:
(define-keyset 'admin-keyset (read-keyset "admin-keyset"))
(module complex-schema 'admin-keyset
(defschema data
a : decimal
b
)
(defschema table-schema
v : {data}
)
(deftable my-table:{table-schema})
(defun new-thing (id:string)
(insert my-table id {
"v" : {"value":100.0,"rate":0.5}
})
)
)
REPL输出/交互
pact> (load "complex-schema.repl")
"Loading complex-schema.repl..."
"Setting transaction keys"
"Setting transaction data"
"Begin Tx 0"
"Loading complex-schema.pact..."
"Keyset defined"
"Loaded module complex-schema, hash tGl1sYgL1VWh8zBJCU3KmMGbofkzK0gBEyXwbRnp7sI"
"Typecheck complex-schema: Unable to resolve all types"
:OutputFailure: Unable to unify field type: (v, {complex-schema.data}, (object:*, Object object5::object:* {"rate": Prim decimal6::decimal = LDecimal {_lDecimal = 0.5},"value": Prim decimal7::decimal = LDecimal {_lDecimal = 100.0}}))
"Verification of complex-schema failed"
:OutputFailure: Unable to unify field type: (v, {complex-schema.data}, (object:*, Object object4::object:* {"rate": Prim decimal5::decimal = LDecimal {_lDecimal = 0.5},"value": Prim decimal6::decimal = LDecimal {_lDecimal = 100.0}}))
"Commit Tx 0"
"Begin Tx 1"
"Using complex-schema"
"TableCreated"
"Commit Tx 1"
pact> (use complex-schema)
"Using complex-schema"
pact> (new-thing "123")
<interactive>:1:0: Type error: expected (defschema data [a:decimal, b:<a>]), found object:*
at : (insert (deftable my-table:(defschema table-schema [v:(de... "123" {"v": {"value": 100.0,"rate": 0.5}})
at <interactive>:0:0: (new-thing "123")
我不确定它是否正是您想要的,因为我在表中省略了显式类型定义。但它允许我加载您的模块,并调用它的函数在my-table
:中插入记录
(module complex-schema 'admin-keyset
(defschema data
a : decimal
b )
(defschema table-schema
v
)
(deftable my-table:{table-schema})
(defun new-thing (id:string)
(insert my-table id
{
"v" : {"a":100.0,"b":0.5}
})
)
(defun read-thing (id:string)
(with-read my-table id { "v":= thing:{data} }
(format "Property a is {} b is {}" [(at 'a thing) (at 'b thing)]))
)
)
"Loaded module complex-schema, hash BuS1-Ez49mdvVuflRmWmJBJMmgq0nOl3XqAeSGLx_fM"
pact>
(create-table my-table)
"TableCreated"
pact>
(new-thing "test")
"Write succeeded"
pact> (read-thing "test")
"Property a is 100.0 b is 0.5"
您可以在读取对象时应用类型定义:
(with-read my-table id { "v":= thing:{data} } ..
然后将对象的属性与(at 'property objectname)
一起使用