Avoiding copy/paste code for similar queries in sqlite? - sqlite

I'm new to sqlite. For a game I'm working on I need a simple view of the top 5 values of a property with their associated player, which works fine like this:
SELECT
player,
reputation,
races.name,
races.color
FROM
games_player
INNER JOIN
races ON races.id = games_player.race
ORDER BY
reputation DESC
LIMIT 5
I can save this view in the database using DB Browser for SQLite. However, I need 3 more of those, for properties other than "reputation" (e.g. "strength" or whatever). I can easily create these views by duplicating the code and modifying the property name in each one, but if I later need to add some slight modification to the query format (even if it's only the ORDER BY value), I'll need to do it four times.
Is there a mechanism such a variable, an include system or anything else that can help me avoid this?

Related

APEX 4.1 SQL Query using a page item to define FROM

I am trying to utilize a single tabular form to handle a couple minor tables since I cannot have multiple updateable reports on a single page. The easiest way I could figure to adjust what table I was modifying was to use a select list to choose which table I am viewing/editing.
The select list contains a display of "Supervisor" and "School"
resulting in SUPERVISOR and SCHOOL respectively
the items name is P8_TABLE
Region Source:
select *
from #OWNER#."G06_" || :P8_TABLE
The tables are named G06_SUPERVISOR and G06_SCHOOL
However the query returns:
ORA-00933: SQL command not properly ended
I'm afraid that this won't work. As far as I can tell, tabular form is to be based on one table only (i.e. you can't have a JOIN in there; even if you're displaying values from some other table, you'd rather create functions which would return those values).
That being said, principle you'd like to use means that tabular form underlying table is unknown (as it can vary, depending on what you select in P8_TABLE select list item), which - in turn - means that column names also differ (unless all of those tables share the same column list).
If we presume that above is correct, then I'd suggest you to abandon that approach and maintain every "minor table" on its own tabular form page. It will be just a little bit more typing & clicking, but I wouldn't worry about it.
Hopefully, someone else knows how to do it the way you'd want it to.
You cant make a tabular form query source dynamic. And since the two tables you want to be displayed and be updatable doesnt have common number and usage of their columns, the only way I can think of is separating the two tables and diplaying one tabular form for each table. Though, Apex 4.1 or even the latest Apex 5 doesnt allow multiple tabular form, you can make this possible by using javascript's iframe. You'll need to use javascript since you want to modify the interface of the report/page.

How to use cursors for navigating to previous pages using GQL and the new gcloud-java API?

I'm using the new gcloud-java API (https://github.com/GoogleCloudPlatform/gcloud-java/tree/master/gcloud-java-datastore/src/main/java/com/google/cloud/datastore) for working with the Cloud Datastore. My specific question is on using GQL for pagination with cursors. I was able to page through the results one page at a time in the forward direction using cursors, but not having any luck with paging backwards.
Example Scenario:
Let's say I've 20 entities in a Kind with IDs 1 through 20. I have a page size of 5. Once I'm on the 3rd page (IDs 11 through 15), if I need to go one page back; i.e. retrieve IDs 6 through 10, what would be the correct GQL/sample code? Again, I prefer not to use offset with a number, but would like to use Cursors.
From what I can tell (actually tested), it looks like one needs to keep track of Start/End cursors for each page as they navigate in the forward direction, then use the saved cursors when there is a need to go back. I just want to make sure if this is the correct/only way or there is a simpler way to accomplish this.
Thanks in advance for your help.
If you add to your original query a sort by key (appended to the end of your "order by" clause), you should be able to reverse each property's sort order and use the latest cursor from your original query to get results in reverse.
Suppose you've iterated through some of the values from your forward query's QueryResults. You can call QueryResults's cursorAfter() method, which will return a cursor pointing right after the last result you saw from your original query. Now you can issue a new query (with the opposite sort order on each property, including the key property) using that cursor as the start cursor. You'll probably want to skip the first result, since it will be the last result you saw from the original query.

Access 2010 Query with Parameter and Sort

I have a problem that I've been going round and round with in Access 2010. Imagine a table with these columns:
Name Date Time
Now, I have a query that asks the user to input a begin date and an end date and returns all records that are between those two dates. This works fine. However, as soon as I add a sort to the Date column things go awry. Once you put a sort on a column with a parameter the user gets asked to enter the parameter twice. From what I've been able to find out this is normal (although annoying) behavior in Access.
If I add the Date column in a second time and show the column with the sort and don't show the column with the parameter it works fine. The query would look something like:
Name Date (shown & sorted) Date (not shown & parameters) Time
Now when I run the query it all works well and comes out the way I want it to. This would obviously be a great solution then. However, there's another problem. When I save the query, leave, and reopen the query the two columns are merged back into each other. Thus, the change is lost and the user again sees two inputs.
My question is this: what can I do differently to achieve the desired results?
Some possible things I've thought about but don't know the answer to are:
Is there a way to make it so the columns don't merge? Do I have to use a form with the input boxes and take the data from that (I'd prefer not to do that as it will require a lot of additional work to handle the various things I am doing in the database). Is there some obvious thing I'm missing?
Thanks for any suggestions.
FYI: Here is the SQL from the query
SELECT Intentions.Intention, Intentions.MassDate, Intentions.[Time Requested], Intentions.[Place Requested], Intentions.[Offered By], Intentions.Completed
FROM Intentions
WHERE (((Intentions.MassDate) Between [Enter start date] And [Enter end date]))
ORDER BY Intentions.MassDate, Intentions.[Time Requested];
It is true that sometimes the Query Designer in Access will "reorganize" a query when you save it. However, I don't recall an instance where such a reorganization actually broke anything.
For what it's worth, the following query seems to do what you desire. After saving and re-opening it looks and behaves just the same:
For reference, the SQL behind it is
PARAMETERS startDate DateTime, endDate DateTime;
SELECT NameDateTime.Name, NameDateTime.Date, NameDateTime.Time
FROM NameDateTime
WHERE (((NameDateTime.Date) Between [startDate] And [endDate]))
ORDER BY NameDateTime.Date DESC , NameDateTime.Time DESC;
I have had the same problem and I have discovered the reason:
If, after you have run your query, sort a collumn in the result grid and the say yes to save changes to the query the sort action will be stored with the query. This will actually cause the query to run twice. First to create the result and then one more time to sort. You'll therefore be asked twice for the parameters.
SOLUTION: Run the query (entering your parameters twice ;-) ). Then remove the Sorting by clicking on the AZ-eraser symbol in the task bar above (in the sorting compartment).
Then open your query in design-mode and add the sorting order to the appropriate collumn.
Your are then good to go.
Regards
Jan

Qt: QSqlTableModel + QTableView sync with PostgreSQL

I'm writing a database access app for storing some data and want to ask a few questions about the model/view architecture.
(Using: Qt 4.7.4, own build; PostgreSQL 9.0; Targets: WinXP, Win7 (32/64 bit))
Let me first explain what I am trying to achieve and where I am currently.
I have two pages (subclassed QWidgets inserted in a QStackedWidget) with a QTableView bound to a model. Each view is bound to a table in the PostgreSQL server. You can add/edit/delete/sort/filter items.
Each page can be seen by only one type of users, lets call the roles Role1 and Role2.
The submit strategies of everything connected to the model are OnManualSubmit.
(Transaction isolation level = Serializable.) When two users want to edit(for example) the same row, I want to do a "SELECT ... FOR UPDATE" query - to make sure that when someone edits something, he will merge his changes with newer ones (if any, just like in SVN for example). But I see only a submitAll() method the QSqlTableModel.
Maybe catching the signals beforeUpdate(), beforeDelete(), beforeInsert() and performing manually "SELECT ... FOR UPDATE" is one option.
The other way I think is to subclass QSqlTableModel. What is the clean and nice way to achieve this?
I want to periodically update the QSqlTableView for each of the pages (one page is seen at most, Role1 users have access only to Page1 and the same for Role2 => Page2).
The first thing that came to my mind is to use a QTimer and manually call select() of the QSqlTableModel, but... not sure if this is the cool way.
I also want to periodically check if the connection to the database is ok, but I think that a QTimer + QSqlDatabase::isOpen () will do.
Now, the 2 tables have the same primary keys and some columns are the same. I want when a user with Role1 changes a row in Table1 to automatically change corresponding columns of Table2 and vice versa. Should I create a trigger in Postgres?
BTW, the database is small - each of the two tables is around 3-4000 rows with ~10 columns (varchars mostly, 1 text and 2 date colunms).
Thanks for reading and Happy New Year! :)
I think you should consider doing something of the following:
Instead of using QSqlTableModel as a model I'd implement my own model as a subclass of QAbstractTableModel. This will allow you a lot of control over what you can do in terms of data manipulation.
One thing that this will require is for certain fields in the table you would need to implement subclass of QAbstractItemDelegate that will allow for modification of data in the table as I am fairly sure you don't want to allow users updating any field in the table as for example primary key is likely have to be left alone.
For question 2 I would suggest implementing a field called transaction_counter for every row so you don't have to select every row in the table just the updated ones the transaction_counter will be updated on every row update and the new one will be inserted on the new row insert. One thing that will be required is that the counter is unique across the table. For example if initial state of the table is: row1 has counter = 0 and row2 has counter = 0. If row1 is updated counter set to 1. When row1 is then updated again counter on it is set to 2. When row2 is now updated counter on it is set to 3, etc. You can certainly do the data refreshes now using QTimer and this will be much more advantageous to for example checking the data as one user may be updating the same table as another user with the same Role.
For Question 3. I don't see any reason why not custom models and especially if you decide to separate data from the model you can manipulate data separately from it's display. Sort of Data->Model->View->Controller implementation. Each one can be maintained separately as long as you have a feedback mechanism for your delegates.
For Question 4. The answer is sure or you can implement the trigger in your application.
Hope this helps. Have a great New Year!

Handling SortOrder fields in SQL Server

In a specific table I have a SortOrder integer field that tells my page in which order to display the data. There are sets of data in the this field (based on a CategoryID field), and each set will have its own ordering. Users can add/remove/update records in this table.
My question is what is the best way to manage this SortOrder field? I would like to "reseed" it everytime a record is deleted or updated. Is this something I should be using a trigger for? Or should my code handle it and manage the reseeding?
What I used to do is use only odd numbers in the SortOrder field so upon changing the order, I would add or subtract 3 from the current value of the modified item and then do a reseed (order the items again using odd number indexes). Also I used to reseed after every insert or delete.
All you really have to worry about is swapping any two fields. All new entries go to the end and i'm sure you've got a mechanism by which the user can change the order. The order change, move up or down, really is a swap with a neighboring field. All you really care about is that all the fields are sorted properly. Don't let a mathematical sense of aesthetic drive you into creating something overly complex. (You'll end up with holes in your sequence after deletes are made but that's OK. It's an internal sequence marker used for ORDER BY. the numbers don't need to be made contiguous.)

Resources