How to search in existing contracts? e.g. find the Account contract in existing Accounts by using accountid - daml

What should I do to find an existing contracts?
e.g. I have a template which create Account contract. Before creating the contract, I need to search the existing contracts to make sure the account id is not duplicated.

As Shayne Fletcher points out, DAML recently gained a feature called "Contract Keys" which addresses the specific issue you are trying to solve. You make use of this feature by declaring a key on a template together with a set of maintainers, who ensure the uniqueness constraint in that key and validate any lookups.
template Account
with
issuer: Party
owner: Party
accountNo: Text
where
signatory issuer
observer owner
key (issuer, accountNo) : (Party, Text)
maintainer issuer
The above specifies that the tuple (issuer, accountNo) is the "primary key" of this type of contract and that the issuer of an account is responsible for maintaining the index for accounts issued by them.
You now have two functions at your disposal: fetchByKey and lookupByKey. Both take a tuple (Party, Text). fetchByKey returns a tuple (ContractId Account, Account) and aborts the transaction if the key can't be found. lookupByKey returns an Optional (ContractId Account), with the additional subtlety, that the use of lookupByKey must be authorised by the issuer.
More generally, though, queries tend to be done off-ledger, in the integration layer of the application. If, for example, you wanted to check that a given owner doesn't hold more than 10 account already, you would typically do that by maintaining a mirror of the active Account templates in a queryable database of your choice and querying that before submitting your transaction.
You can have a look at this example, which maintains all active contracts in a MongoDB.

Related

Is there a way to get the check digits of card master key or the session key used for arqc calculation from the chip card?

ARQC validation is not working, I understand there could be several reasons for that, I need to first confirm I have the correct issuer master key. Is it possible to get the check digits of the key(used in arqc generation) from the chip application
Yeah tough to analyze and correct, but unfortunately, KCV is available only for certification authority public key, not for card key or session key.

couchbase per user data approach

having a bit of trouble finding the correct way to model per user data in couchbase and sync up via couchbase mobile for user specific data. In couchdb you have a separate database per user. What is the best approach in couchbase ?
In Couchbase there is no such thing as "user data". Its generic and open for your designs.
Normally when you design your object domain model for Couchbase you would inject metadata in your key structure.
For example:
Key for Account: "Acc#123456789" - where prefix "Acc#" is telling about type of the key, and "123456789" adds particular address instance of this key...resulting in the unique key.
Similarly if you want to encode associated address to the account, you'd architect the following key: "Acc#123456789#Addr" - where postfix "#Addr" identifies type of the key for address object
Now, if you want to have user specific keys, you just simply inject user identifier into the key value (from the example above):
key "Acc#123456789" will transform to "usr#12345#Acc#123456789"
key "Acc#123456789#Addr" will transform to "usr#12345#Acc#123456789#Addr"
Read more on Couchbase data modeling here and keys and metadata
You can create your documents in that way which can able to ease the retrieve all related entity. e.g.
Create your documents with user_{Guid} consider Guid as your UserID
Make all other related document with this same Guid like credential_{Guid} so when user logged in we can have userID in session and get all information of that user.

A User with many Addresses, but User has a primary billing, shipping, and profile Address

I'm building a Rails app where a User can have many Addresses. A User also needs a primary billing Address, primary shipping Address, and primary profile Address. These primary fields can point to the same Address. A User cannot have more than one of any primary Address.
I've created a join table called AddressInfo, and I'm bouncing between a few options:
Make 3 columns on the User model corresponding to each of the primary Address ids (this would remove the need for the join model I think).
Add a primary boolean column to AddressInfo, and make sure only one is true when scoped by user_id, address_id and purpose (purpose being billing, shipping or profile).
Add a primary date time column to AddressInfo, and use the most recently updated as the primary address (scoped like option 2).
Maybe these options aren't the best, but it's what I've come up with so far.
Any help on how to resolve this issue would be appreciated.
UPDATE:
To be clear, once an Address is created it should always belong to that User and be undeletable. Ex. a User changes their primary billing address to a new Address: they should still be able to retrieve that old Address (maybe even make it a primary address again). If I go with option 1 and remove the join table, that means I'll need a user_id on Address.
Go with option 1, 3 columns. This will make less of a headache (as a programmer), will run faster, and is more flexible for doing things like combining similar addresses into one. Maybe you have 2 people with the same address, they could share the same record (not recomeneded though).
If you're using rails I would look to a rails solution to 'stay on the rails'.
I would consider STI (Single Table Inheritance)
More info at Rails: Need help defining association for address table
or a Polymorphic relationship - http://guides.rubyonrails.org/association_basics.html#polymorphic-associations
As you want 1 user to have multiple address (rather than ther being multiple user types) than STI may be best for you.
Note: they can also be combined, e.g. http://www.archonsystems.com/devblog/2011/12/20/rails-single-table-inheritance-with-polymorphic-association/
There's a great example of STI addressing this issue at: http://blog.arkency.com/2013/07/sti/
Another possibility is to create another model to hold user.id, addressinfo.id, and an primary_for_address_type (containing "Shipping", "Profile", "Billing").
Constrain this to be unique on user and primary_for_address_type, and you can tag addresses in AddressInfo as being the primary for particular address types in a completely extensible way that still guarantees uniqueness of the primary address.
You might join directly from this model to address, but there's scope for getting it out of sync with your addressinfo model.

Using Database Primary Key in HTML ID

Just wanted to ask.
I have site where each user is linked to an ID in the Database and this Primary Key is included in many tables. The fastest way for me to pull a users information is to have this ID.
Would it be considered bad practice to put this ID in website HTML code? eg id="theIDnumber"
Otherwise i can just use the username and then reference this in the Database for this ID - which is fine but using the ID would be faster I believe.
thoughts?
I'd say no, if your keys are predictable. A trivial example: if you are using sequentially incrementing primary keys users can extract information from data that could be a privacy concern. e.g. they can infer which account was created before their account. Life also becomes easy for those trying to systematically leech information from your site.
Some related reading
https://stackoverflow.com/a/7452072/781695
You give your end users the opportunity to mess with those variables
and pass any data that they like. The counter measure to mitigate this
vulnerability is to create indirect object references instead. This
may sound like a big change, but it does not necessarily have to be.
You don't have to go and rekey all your tables or anything, you can do
it just by being clever with your data through the use of an indirect
reference map.
https://security.stackexchange.com/a/33524/37949
Hiding database keys isn't exactly required, but it does make life
more difficult if an attacker is trying to reference internal IDs in
an attack. Direct references to file names and other such internal
identifiers can allow attackers to map the internal structure of the
server, which might be useful in other attacks. This also invites path
injection and directory traversal problems.
https://www.owasp.org/index.php/Insecure_Direct_Object_Reference_Prevention_Cheat_Sheet
An object reference map is first populated with a list of authorized
values which are temporarily stored in the session. When the user
requests a field (ex: color=654321), the application does a lookup in
this map from the session to determine the appropriate column name. If
the value does not exist in this limited map, the user is not
authorized. Reference maps should not be global (i.e. include every
possible value), they are temporary maps/dictionaries that are only
ever populated with authorized values.

Always create unique keys whenever possible?

Should you always create unique keys whenever possible?
For example let's say I have a table with three fields, student ID, first name, last name and the student ID is the primary key.
If no two students have the first & last name, should I create a unique key for those two fields?
Yes, you should use unique indexes even when you already have a primary key when the column or combination of columns are unique. It's good to have constraints in your database to prevent bad data. However, this is not what you have in your case. Even if you currently have no students with duplicate names that can easily happen in the future. Names are not unique in the world.
U.S. Social Security numbers are almost always unique (they can be reused after a number of years, but it's unlikely to ever happen in your case), so they might make for a good candidate for a unique index. If you have non-U.S. students though then you would need to make the column nullable.
Yes, usually having unique IDs (surrogate keys) is best. In this case, last name and first name are not enough for a primary key. Even if you no duplicate names now, you can't be sure you won't have two John Smith's in the future.
Don't make the assumption that no two students will have the same name.
When the underlying model suggests it, it is a good idea to create unique keys. Constraints like these will ensure cohesive data and prevent errors. But in your case the underlying model does not suggest this to be the case.
Unique keys should follow business definitions; if the studentID is a "semi-natural" key (it has unique meaning that exists beyond your specific database), then that should suffice as your unique key.
If the studentID is simply an identity value that is assigned by the database as a row-number, then you probably need some other unique key to avoid entering the same student twice.
Primitive primary key with no relation to data domain is one of widely accepted best practices
( just imagine - one of your students decides to marry )
Another good practice (though from NoSql) world is to use GUID - this way keys are unique, and different datasets can be mixed in same table without collisions.
PS: you could save some storage space, but today it is cheap and there is no need to sacrifice good practices for it
Yes!
If you ever need to update or delete rows from the table, it is very advantageous to have something to uniquely identify each row in the table.
With your example, I don't think it's possible to guarantee no two students will share the same name. Even adding a date of birth still can't guarantee they'll always be unique. I'd recommend adding an auto incrementing INT or BIGINT as the primary key.
You can always add the Unique constraint as well and remove it if it becomes an issue.
A simple way to do it is use an auto-generated Guid (Globally Unique Identifier) to identify a student. It is "guarenteed" to be unique every time it is generated. Names can change (like when somebody gets married), but some auto generated value has no meaning so should never need to be changed.
http://en.wikipedia.org/wiki/Globally_unique_identifier
Your database constraints should be DBMS understood business rules. Is there a business rule that states that no two students may have the same first and last name combination? I presume not, therefore do not create a unique key for those two fields. Perhaps best not to presume, though, and ask a business domain expert e.g. the enrolment officer.
Note that a row in this table is a proposition I.e. that there exists a student enrolled with first name 'x' and last name 'y' and student ID 'z'. Clearly the DBMS has not concept of whether this proposition is true in the real world. What normally happens is that there will be a trusted source to verify data. The enterprise will authorize an officer (director etc) in this role. Let's say it is the enrolment officer who is responsible for verifying that 'x y' is a real person, that they are eligible to be enrolled, and the person is who they say they are. Typically, they will require sight of documents (certificates, passport, etc), take up references, interview the person, check public records, etc. Of course, the enrolment officer may delegate their responsibility to other members of staff or engage an agent.
At some point they will be satisfied and for convenience will issue they own identifier, the student ID. Mistakes do happen and it may turn out that this value is not unique, in which case it would be the enrolment officer's responsibility to resolve the problem and issue a new student to. Perhaps they will use software to generate the value to mitigate against such problems. The student ID will be issued to the student and will be used within the enterprise to identify the person for the convenience of all concerned. They may even be issued with a document (e.g. photo ID card) to assist in identification, based on the level of trust in a given context (e.g. may need to produce photo ID to sit an exam). If the student forgets their ID, loses their issued documents, etc then the enrolment office will be able to retrieve it from records e.g. with reference to copy documents taken during the verification process; they are unlikely to use first name and last name alone.
The point is, the trusted source for the identifier is the enrolment officer on behalf of the enterprise, rather than the database, the DBMS or any other kind of software involved in the process. Therefore, it probably is acceptable to make student ID the sole identifier for stents within the database. Consider, however, that an auto-increment column generated on one hardware build of a single DBMS within the enterprise is probably not suitable for the allocation of such significant identifier values.