How to implement database engine UPDATE command - java

I am developing a simple database engine in Java (using text files as tables) and I have to implement code for CRUD operations. I have successfully written code for CREATE and INSERT commands already. Now I want to continue with UPDATE which should look like this:
UPDATE table-name SET attribute-name=literal {,attribute-name=literal} WHERE condition
But I have an issue here, I am stuck with "condition". How can I approach the implementation of a condition? (WHERE attr1 = something AND attr2 >= something OR . . .) I will very much appreciate your feedback.
Best regards.

The WHERE part is always the most important component of any database system. To find out all the records satisfying the conditions in WHERE part, you should build proper indexes for any columns included in the condition.
For example, you will find WHERE attr1 = something AND attr2 >= something OR...
, then columns attr1, attr2 must have been indexed, otherwise it will take terrible long time to perform.
Index techniques may be hash index (for K-V search), B+ tree index and all their derived implementations.

Related

how to choose or write my own java data structure allowing multi attributes search

I have a pretty large list containing many instances of one class, this class has many attributes(member variables). My problem is to find a feasible data structure to store these instances that allow searches based on multiple attributes like database search(i.e. A Student class, each student has age, date of birth, grade and GPA.find all 2nd year students whose ages are between 20 and 23). The Map seems not applicable as it only allow single key and if I create multi attribute index for searching, the big O is still not decreased. I also considered using trees like AVL tree, and I don't think it would work.
I'd be grateful if someone could give me some hints.
I think what you are looking for is an Inverted Index (using attribute name + value as keys) or possibly one Inverted Index per attribute. A search would build the intersection of all results found for each attribute.
You could do this:
Build an AVL tree with objects sorted by the most recurrent attribute (just one, e.g. "id" or "name").
Then create a search function that instead of taking a value, takes a Java lambda expression F (so your seacrh condition must be something like F(myObj) == true instead of myObj.deFaultAttribute == searchParameter)
For the example you gave, F could be something like ((myObj) -> myObj.year==2 && myObj.age>=20 && myObj.age<=23)
I hope it helps.

ORDER BY with SUM, MIN, MAX, etc using Ebean

I am using PlayFramework 2.2.2 with Ebean and MsSql.
I am looking for the simplest or cleanest method to be able to sort by MIN or MAX etc.
A sample raw sql query might look like:
SELECT id, name, tickets FROM users WHERE tickets != NULL ORDER BY MAX(tickets)
I don't know if it's just me, but the documentation for ebean is incredibly confusing. It seems any time anyone comes up with a query that couldn't be written by a 9 year old, the answer is "switch to RawSQL". Well, why bother with Ebean at all then?
Anyway, I would really like to see some CONCRETE Ebean examples of ordering by MIN/MAX, etc.
Do you really need order by min ,max... since there is id in the select list.
Let me know whether id is unique or duplicates are allowed
Would suggest to use the following query incase the id is unique
select id,name,tickets from users where tickets is not null order by ticket desc
I encountered the same problem then I found the following information.
Design Goal:
This query language is NOT designed to be a replacement for SQL. It is designed to be a simple way to describe the "Object Graph" you want Ebean to build for you. Each find/fetch represents a node in that "Object Graph" which makes it easy to define for each node which properties you want to fetch.
Once you hit the limits of this language such as wanting aggregate functions (sum, average, min etc) or recursive queries etc you use SQL. Ebean's goal is to make it as easy as possible to use your own SQL to populate entity beans. Refer to RawSql .
-> http://www.avaje.org/static/javadoc/pub/com/avaje/ebean/Query.html

How to determine if a table contains a value in SQL?

I feel like I'm missing something very obvious here, but it seems that the only way to go about doing this is to get the value, and then see if it returns a null (empty) value, which I would rather not do.
Is there an equivalent to List.contains(Object o) in SQL? Or perhaps the JDBC has something of that nature? If so, what is it?
I am using Microsoft Access 2013.
Unfortunately I don't have any useful code to show, but here is the gist of what I am trying to do. It isn't anything unique at all. I want to have a method (Java) that returns the values of a user that are stored in the database. If the user has not previously been added to the database, the user should be added, and the default values of the user should be set. Then those newly created values will be returned. If a player has already been added to the database (with the username as the primary key), I don't want to overwrite the data that is already there.
I would also advise against using MS Access for this purpose, but if you are familiar with MS Office applications, the familiar UI/UX structure might help you get your footing and require less time to learn other database environments. However, MS Access tends to be quite limited, and I would advise considering alternative options if available.
The only way to see if an SQL table contains a row with some condition on a column is to actually make an SQL query. I don't see why you wouldn't do that. Just make sure that you have an index on the column that you will be constraining the results on. Also for better speed use count to prevent from retrieving all the data from the rows.
SELECT count(*) FROM foos WHERE bar = 'baz'
Assuming you have an index on the bar column this query should be pretty fast and all you have to do is check whether it returns > 0. If it does then you have rows matching your criteria.
You can use "IF EXISTS" which returns a boolean value of 1 or 0.
select
if(
exists( select * from date1 where current_date()>now() ),
'today > now',
'today is not > now'
) as 'today > now ?' ;
+--------------------+
| today > now? |
+--------------------+
| today is not > now |
+--------------------+
1 row in set (0.00 sec)
Another Example:
SELECT IF(
EXISTS( SELECT col from tbl where id='n' ),
colX, colY
) AS 'result'
FROM TBL;
I'm also new to sql and I'm using Oracle.
In Oracle, suppose we have: TYPE: value.
We can use:
where value not in (select TYPE from table)
to make sure value not exist in the column TYPE of the table.
Don't know if it helps.
You can simply use Query with condition.
For example if you have to check records with particular coloumn, you can use where condition
select * from table where column1 = 'checkvalue'
You can use count property to check the no. of records existing with your specified conditon
select count(*) from table where column1 = 'checkvalue'
I have created the following method, which to my knowledge works perfectly. (Using the java.sql package)
public static containsUser(String username)
{
//connection is the Connection object used to connect to my Access database.
Statement statement = this.connection.createStatement();
//"Users" is the name of the table, "Username" is the primary key.
String sql = "SELECT * FROM Users WHERE Username = '" + username + "'";
Result result = statement.executeQuery(sql);
//There is no need for a loop because the primary key is unique.
return result.next();
}
It's an extremely simple and extremely basic method, but hopefully it might help someone in the future.
If there is anything wrong with it, please let me know. I don't want anyone learning from or using poorly written code.
IMPORTANT EDIT: It is now over half a decade after I wrote the above content (both question and answer), and I now advise against the solution I illustrated above.
While it does work, it prioritizes a "Java-mindset-friendly" approach to SQL. In short, it is typically a bad idea to migrate paradigms and mindsets of one language to another, as it is inevitable that you will eventually find yourself trying to fit a square peg into a round hole. The only way to make that work is to shave the corners off the square. The peg will then of course fit, but as you can imagine, starting with a circle peg in the first place would have been the better, cleaner, and less messy solution.
Instead, refer to the above upvoted answers for a more realistic, enterprise-friendly solution to this problem, especially as I imagine the people reading this are likely in a similar situation as I was when I originally wrote this.

Using operator 'or' in Cassandra IndexExpression

I have an Java application with Cassandra db. I'm using Cassandra Pelops. I have a columnFamily cf1, and a lot of columns there. For some of them I created secondary index, so I can use them for search. For search purpose, I created a list of IndexExpression (expressions), for example:
final IndexExpression propertyIdExpression = new IndexExpression(
ByteBuffer.wrap(Bytes.fromUTF8(CassandraIntegrationDAOHelper.COL_PROPERTY_ID).toByteArray()),
IndexOperator.EQ,
ByteBuffer.wrap(Bytes.fromInt(entity.getProperty().getId()).toByteArray())
);
expressions.add(propertyIdExpression);
Now I need to include some additional check. I have columns dateFrom and dateTo. Requests is to return all rows where this two dates are in some interval. They don't have to be completely in the interval, important is to start or end in this interval. So, I need to somehow implement something like this:
if( (dateTo is greaterThan intervalStart) or (dateFrom is lowerThan intervalEnd) )
by using IndexExpression. Any suggestions? I hope I was clear! Thanks in advance!
Cassandra does not support disjunction ("or") in secondary index queries at this time, only conjunction ("and"). In most cases, it's sufficient to make two separate queries with each half of the disjunction and combine the results.
However, if you're dealing with time ranges, that's something you should be using column names for, not secondary indexes. I suggest checking out some of the documentation on time series data and thinking about how to restructure your data to support efficient queries based on time ranges.

Hibernate getting position of a row in a result set

I need to get an equivalent to this SQL that can be run using Hibernate. It doesn't work as is due to special characters like #.
SELECT place from (select #curRow := #curRow + 1 AS place, time, id FROM `testing`.`competitor` JOIN (SELECT #curRow := 0) r order by time) competitorList where competitorList.id=4;
My application is managing results of running competitions. The above query is selecting for a specific competitor, it's place based on his/her overall time.
For simplicity I'll only list the COMPETITOR table structure (only the relevant fields). My actual query involves a few joins, but they are not relevant for the question:
CREATE TABLE competitor {
id INT,
name VARCHAR,
time INT
}
Note that competitors are not already ordered by time, thus, the ID cannot be used as rank. As well, it is possible to have two competitors with the same overall time.
Any idea how I could make this work with Hibernate?
Hard to tell without a schema, but you may be able to use something like
SELECT COUNT(*) FROM testing ts
WHERE ts.score < $obj.score
where I am using the $ to stand for whatever Hibernate notation you need to refer to the live object.
I couldn't find any way to do this, so I had to change the way I'm calculating the position. I'm now taking the top results and am creating the ladder in Java, rather than in the SQL query.

Categories