api_java
评论(0) 浏览量(150)

Basic Operation

c

c -> c

ChainSQL operation object;

Example: Acquisition ChainSQL operation object;

import com.peersafe.ChainSql.modle.Chainsql;
import com.peersafe.ChainSql.modle.Table;
import com.peersafe.ChainSql.net.Connection;

public static final Chainsql c= Chainsql.c;

connect

c.connect(url);

Create a new connection to the ChainSQL node;

If it cannot establish a connection, it will throw ReqlDriverError;

Example: Connect the specified path host.

c.connect("ws://192.168.0.162:6006");

as

c.as(address,secret);

Provide the identity of the operator;

c.as("rEtepyQeAEgBLqXCaFRwZPK1LHArQfdKYr","snrJRLBSkThBXtaBYZW1zVMmThm1d");

use

c.use(address);

Switch the owner of the table (the context of the subsequent operation), the default owner of the table is operator;

c.use("rEtepyQeAEgBLqXCaFRwZPK1LHArQfdKYr");

setRestrict

c.setRestrict(true/false);

Set whether to use strict patterns and defaults to non strict patterns; in strict mode, the statement consensus is passed by the desired snapshot HASH consistent with expectations;

c.setRestrict(true);

submit

c.submit();

Submit has 3 overloaded functions that correspond to asynchrony and synchronization, and clients can fill in the parameters as needed. The returned values are JSON objects indicating success or failure;

1. JSONObject  submit()

Asynchronous interface, parameter is null;

c.submit();

Submission operation. When performing query operations, return the JSON type;

c.table("marvel").submit();

2. JSONObject  submit(Callback cb)

Asynchronous interface. The parameter is a callback function;

The callback function takes the form of JAVA8, such as:

(data)->{//do something here}

c.table("marvel").submit((data)->{//do something here});

3. JSONObject  submit(SyncCond cond)

A synchronous interface with an enumerated parameter;

enum SyncCond { validate_success, db_success, }

c.table("marvel").submit(db_success);

User management

generateAddress

c.generateAddress();

Create user, return the account information, account contains the secret: secret key, account_id: account address, public_key: public key;

Example: JSONObject json = c.generateAddress();

pay

c.pay(accountId,count).submit();

For the user who created the transfer, the newly created user will not be able to use it until the transfer is successful. AccountId is the user's address for the transfer, and count is the amount of the transfer. The minimum count value is 20;

Example: Transfer account number to address rBuLBiHmssAMHWQMnEN7nXQXaVj7vhAv6Q for 20

c.pay("rBuLBiHmssAMHWQMnEN7nXQXaVj7vhAv6Q",20).submit();

Table Operation

createTable

c.createTable(tableName,raw);

created table name, raw: created table field name must be Json format data, such as:

"{'field':'id','type':'int','length':11,'PK':1,'NN':1,'UQ':1,'AI':1}",

"{'field':'name','type':'varchar','length':50,'default':null}",

"{'field':'age','type':'int'}"

Create a table. ChainSql table is a collection of JSON documents;

Example: Create table  "dc_universe"

c.createTable("dc_universe",c.array(

"{'field':'id','type':'int','length':11,'PK':1,'NN':1,'UQ':1,'AI':1}",

"{'field':'name','type':'varchar','length':50,'default':null}",

"{'field':'age','type':'int'}"));

renameTable

c.renameTable(tableName, NewTableName);

Modify the database table name, tableName: table name; NewTableName: new table name, two names can not be empty;

Example:  Changed table"dc_universe"to"dc_name".

c.renameTable("dc_universe","dc_name");

dropTable

c.dropTable(tableName);

Delete a table from database. The table and all data will be delete;

Example: Delete table "dc_universe".

c.dropTable("dc_universe");

Data Operation

insert

c.table(tableName).insert(raw).submit();

Inserting data into a database. The raw type must be the data type of the JSON format in the example;

Example: Inserts a record into the table"posts".

c.table("posts").insert(c.array("{'name': 'peera','age': 22}","{'name': 'peerb','age': 21}")).submit();

update

c.table(tableName).get(raw).update(raw).submit();

Update table data. If get add is empty, then updated all records in the table ; raw is a JSON format string;

Example: Updateid equals 1 records.

c.table("posts").get(c.array("{'id': 1}").update(c.array("{'age':'52','name':'lisi'}")).submit();

delete

c.table(tableName).get(raw).delete().submit();

Delete the data from the table,if the get condition is empty, then delete all data;

Example: Deletes idequals1records.

c.table("comments").get(c.array("{'id': 1}")).delete().submit();

Data Query

get

c.table(tableName).get(raw).submit();

Query data from the database, then other operations can be proceed, such as update, delete, etc.;

Example: Query record which nameequals aa.

c.table("posts").get(c.array("{'name': 'aa'}")).submit();

limit

c.table(tableName).get(raw).limit("{index:0,total:10}").withFields([*]).submit();

Paging queries to the database. Return the data for the corresponding condition;

Example: Query name is equalaafiltering the first 10 records.

c.table("posts").get(c.array("{'name': 'aa'}")).limit("{index:0,total:10}").withFields([*]).submit();

order

c.table(tableName).get(raw).order(["{id:1}","{name:-1}"]).withFields([*]).submit()

The query data is sorted by the specified field;

Example: Sort ascending by field ID and sort descending by field name;

c.table("posts").get(c.array("{'name': 'aa'}")).order(c.array("{id:1}","{name:-1}")).withFields([*]).submit();

withFields

c.table(tableName).get(raw).withFields([field1,field2…]).submit();

Querying data from a database and returning a specified field, it must be used together with get;

Example: Query record whichnameequalsaa.

c.table("posts").get(c.array("{'name': 'aa'}")).withFields("['name','age']").submit();

Authority Management

grant

c.grant(tableName,user,rightInfo).submit();

Authorize data table operation permissions to users;

flags : permissions to be authorized, for example:{select: true, insert: true, udpate: true,delete:true};

User permissions are the following: Select, Insert, Update, Delete;

Example: Authorize to users Insert、Deleteoperation permissions.

c.grant("Table", "rEtepyQeAEgBLqXCaFRwZPK1LHArQfdKYr","{insert:true,delete:true}");

Transaction

beginTran

c.beginTran();

Transaction begin;

At the beginning and end of the transaction, the insert, update, delete, and assert statements are wrapped in an atomic execution;

In transactional contexts, transaction submission that supports individual statements is not supported

sqlAssert

c.table(tableName).get(jsonObj1).assert(jsonObj2);

Assertion operations in a transaction, assert continues for true, and false rolls back transactions;

JsonObj1: query criteria;

JsonObj2: assertion expression;

Example: In a record of ID equals 1, determine whether age is equal to 52 and name equal to Lisi; if yes, continue; if a condition is not satisfied or the record does not exist, then roll back the transaction;

c.table("posts").get({id: 1}).assert({age:'52',name:'lisi'});

Example: Determines whether the number of rows in a recordset ID equal to 1 is equal to 1, if it continues, and if not, or if the table does not exist, then roll back the transaction;

c.table("posts").get({id: 1}).assert({$rowcount:'1'});

Example: Determines whether table Posts exists, if the table exists, then continues, and if not, then rolls back the transaction;

c.table("posts").assert({$IsExisted:'1'});

rollback

c.rollback();

Rollback, undo transactions;

This transaction will not be packaged and submitted to the block chain network;

commit

c.commit();

Commit transaction;

All operations during this transaction are packaged and submitted to the block chain network;

Example: 

c.beginTran();
c.table("posts").insert({name: 'peera',age: 22},{name: 'peerb',age: 21});
c.table("posts").get({id: 1}).assert({age:22,name:'peera'});
c.table("posts").get({id: 1}).update({age:'52',name:'lisi'});
c.table("comments").delete({id: 1});
c.commit();
  

Block information

getLedger

c.getLedger(option,cb)

option = {"ledger_index",LedgerVersion||"validated"}

The callback function CB takes the form of JAVA8, such as:

(data)->{//do something here}

Get current blockchain information

getLedgerVersion

c.getLedgerVersion(cb)

Gets the current blockchain height information

The callback function CB takes the form of JAVA8, such as:

(data)->{//do something here}

getTransactions

c.getTransactions(address,cb)

Get all transactions in the current account;

The callback function CB takes the form of JAVA8, such as:

(data)->{//do something here}

getTransaction

c.getTransactions(hash,cb)

Get transaction information under a certain hash;

The callback function CB takes the form of JAVA8, such as:

(data)->{//do something here}

event subscription

subscribeTable

c.subscribeTable(owner, tablename, callback);

1.Subscribe to a table

ownerIs the owner address of the table;

tablename is the name of Table;

Example: The user subscribes to table information namedTestName.

c.event.subscribeTable("rsadxc3pw976e3hfaxUijhbR3ye2orJS6x", "TestName",(data)->{//do something here}));

unsubcribeTable

c.unsubcribeTable(owner, tablename);

2. Unsubscribe from a table

Owner Is the owner address of the table;

tablename is the name of Table;

Example: User unsubscribe tableTestName.

c.event.unsubcribeTable("rsadxc3pw976e3hfaxUijhbR3ye2orJS6x","TestName");

subscribeTx

c.subscribeTx(txid, callback);

3. Subscribe to a transaction

txid:The Hash value of the transaction

Example: Users subscribe to transactions for Hash information.

c.event.subscribeTx(txid,(data)->{//do something here}));

unsubscribeTx

c.unsubscribeTx(txid);

4. Unsubscribe from a transaction

txid:The Hash value of the transaction

Example: User unsubscribe transaction Hash information.

c.event.unsubscribeTx(txid);

operator

comparison operators

comparison operators

$eq     equal       {<field>:{$eq:<value>}} or {<field>:<value>}

$ne     unequal     {<field>:{$ne:<value>}}

$lt     less       {<field>:{$lt:<value>}}

$le     less than or equal   {<field>:{$le:<value>}}

$gt     greater       {<field>:{$gt:<value>}}

$ge     great than or equal   {<field>:{$ge:<value>}}

$in     The field value is in the specified array      {<field>:{$in:[<value1>,<value2>,...,<valueN>]}}

$nin    The field value is not in the specified array    {<field>:{$in:[<value1>,<value2>,...,<valueN>]}}

logical operators

Logical symbol

$and and    {$and:[{express1},{express2},...,{expressN}]}

$or     or     {$or:[{express1},{express2},...,{expressN}]}

fuzzy matching

Fuzzy matching

$regex  like "%value%"            { <field>:{$regex: </value/>}}

$regex  like "%value"             { <field>:{$regex: </^value/>}}

Example:

where id > 10 and id < 100

{$and:[{id:{$gt:10}},{id:{$lt:100}}]}


                where name = 'peersafe' or name = 'zongxiang'

{$or:[{name:{$eq:'peersafe'}},{name:{$eq:zongxiang}}]}


where (id > 10 and name = 'peersafe') or name = 'zongxiang'

{$or:[{$and:[{id:{$gt:10}},{name:'peersafe'}]},{name:'zongxiang'}]}


where name like '%peersafe%'

{name:{$regex:'/peersafe/'}}


where name like '%peersafe'

{name:{$regex:'/^peersafe/'}}

没有登录不能评论