Steps required to interract with IndexedDB via Dexie - dexie

Let's say I create a very simple datastore using the steps below:
var db = new Dexie('MyDatabase');
db.version(1).stores({ friends: 'name, age' });
db.friends.add({ name: 'Camilla', age: 25 });
Now, let’s say the user closes their browser and comes back a day later and we need to query the data that we already saved in a datastore that should already exist. Do I need to include both line 1 and line 2 each time before I query the datastore or insert new rows? I’m confused about when I’m required to execute line 2 – is it basically before I do anything to/with the datastore?

You would normally provide the db.version(x).stores({...}) each time you open the database, no matter if it needs to be created, upgraded or just being opened. By providing this info, you will get immediate access to your tables directly on the db object (accessing for example db.friends.toArray() without waiting for db.open() to finish) as samplified below:
var db = new Dexie("friendsDB");
db.version(1).stores({friends: 'id, name'});
// Here you can just access db.friends without waiting for db.open()
db.friends.toArray()
.then(friends => console.table(friends))
.catch(err => console.error(err));
However, it is also possible to open a database dynamically - that is, open an exising database without knowing its tables or indexes. To do that, you just omit the version().stores() part. Just be aware that you wont be able to access tables directly on the db instance and you don't get the magic auto-creation of the database. Tables meed to be accessed through the tables property and table() method, and only after db.open() has completed.
new Dexie("friendsDB").open().then(db => {
console.log("Table names: " + db.tables.map(t => t.name));
return db.table("friends").toArray();
}).then(friends => {
console.table(friends);
}).catch(err => console.error(err));

Related

Yii2- Not able to insert/delete rows using console controller

I am trying to implement email queue in my project which uses CRON.
I am adding a row in one table and deleting a row from another table using CreateCommand of yii2. Database is mysql.
The entire code is executed and it does not display any error. But the rows are not added or deleted from the database.
I have also tried doing the same thing using ActiveRecords but it does not work. Hence I have used CreateCommand.
Below is the code which I am using -
$connection = \Yii::$app->db;
$result = $connection->createCommand()->insert('email_queue_completed', $arrInsert)->execute();
if(!empty($result))
{
$connection->createCommand()
->delete('email_queue', ['id' => $mail->id])
->execute();
}
$arrInsert is an array containing key value pairs of values to be inserted.

How can I change the column name of an existing Class in the Parse.com Web Browser interface?

I couldn't find a way to change a column name, for a column I just created, either the browser interface or via an API call. It looks like all object-related API calls manipulate instances, not the class definition itself?
Anyone know if this is possible, without having to delete and re-create the column?
This is how I did it in python:
import json,httplib,urllib
connection = httplib.HTTPSConnection('api.parse.com', 443)
params = urllib.urlencode({"limit":1000})
connection.connect()
connection.request('GET', '/1/classes/Object?%s' % params, '', {
"X-Parse-Application-Id": "yourID",
"X-Parse-REST-API-Key": "yourKey"
})
result = json.loads(connection.getresponse().read())
objects = result['results']
for object in objects:
connection = httplib.HTTPSConnection('api.parse.com', 443)
connection.connect()
objectId = object['objectId']
objectData = object['data']
connection.request('PUT', ('/1/classes/Object/%s' % objectId), json.dumps({
"clonedData": objectData
}), {
"X-Parse-Application-Id": "yourID",
"X-Parse-REST-API-Key": "yourKEY",
"Content-Type": "application/json"
})
This is not optimized - you can batch 50 of the processes together at once, but since I'm just running it once I didn't do that. Also since there is a 1000 query limit from parse, you will need to do run the load multiple times with a skip parameter like
params = urllib.urlencode({"limit":1000, "skip":1000})
From this Parse forum answer : https://www.parse.com/questions/how-can-i-rename-a-column
Columns cannot be renamed. This is to avoid breaking an existing app.
If your app is still under development, you can just query for all the
objects in your class and copy the value of the old column to the new
column. The REST API is very useful for this. You may them drop the
old column in the Data Browser
Hope it helps
Yes, it's not a feature provided by Parse (yet). But there are some third party API management tools that you can use to rename the fields in the response. One free tool is called apibond.com
It's a work around, but I hope it helps

MySQL/php: I created database and tables, when I try an INSERT I have #1146

I'm writing an installation script in php, this script has to ask the user some data and then store them in a XML file and on a database.
Here is the procedure:
1) Insert data;
2) Save configuration data (such as database name,user,password,host,port) in a XML file
3) Using those data to install a database (I have an empty dump I use to create it)
4) Insert in the "admin" table the first user data (taken from the form in point 1)
Now, everything works fine until point 4.
When I try to access the database MySql always returns my an error #1146 saying that the table doesn't not exists.
This is my custom JSON log:
{
"Status":"KO",
"Reason":"SELECT * FROM bbscp_admin_user; || Table 'adb.bbscp_admin_user' doesn't exist",
"Errno":1146
}
Obviously I checked both with phpMyAdmin and mysql (from cli) and I can say that both DB and Table DO exists.
Here is the part where I create the DB: [this works fine]
$Install = Install::getInstance();
$sqlscript = str_replace("__DBNAME__",
$config_info['dbname'],
file_get_contents('../config/bbscp-base-db.sql')
);
$connection = mysqli_connect($config_info['dbhost'],
$config_info['dbuser'],
$config_info['dbpwd']
) or die("Unable to connect! Error: ".mysql_error());
if(mysqli_query($connection,'CREATE DATABASE '.$config_info['dbname'].';')){
echo 'Database successfully createad';
mysqli_close($connection);
}else{
die('ERROR CREATING DATABASE!');
}
Here the part where I populate the database from the dump (it only add the tables)
$connection = mysqli_connect($config_info['dbhost'],
$config_info['dbuser'],
$config_info['dbpwd'],
$config_info['dbname']
) or die("Unable to connect! Error: ".mysql_error());
if(mysqli_multi_query($connection, $sqlscript)){
echo 'Database successfully imported';
mysqli_close($connection);
}else{
die('ERROR IMPORTING DATABASE');
}
Now the decisive part, I open a connection with the database (using a library that I've developed in the past years and has always worked fine)
$DB = new Database(Install::getInstance());
$Q = new Query();
$DB->connect();
$query = $Q->addNewUser($config_info['nickname'],
$config_info['password'],
$config_info['firstname'],
$config_info['lastname'],
$config_info['email'],
0); // this just returns the query string I need
// the query in this case is:
// INSERT INTO bbscp_admin_user
// (nickname,password,firstname,lastname,mail,confirmed)
// VALUES (the ones above);"
$res=$DB->startQuery($query); // THIS IS WHERE THE ERROR IS RETURNED
// this function only wraps the mysqli_query and returns a custom JSON
I've tried a lot of solution.. The tables DO exists but every query I try to invoke at this point doesn't work because apparently "table doesn't exist" (even using mysqli function instead of mines).
Thanks in advance and sorry for the long question! :-)
EDIT 1
During this days I've changed a lot of code, I tried using different implementation using functions, objects, redirects but none of them seems to work.
The thing is always the same:
It creates the database
Returns the error code when trying to add the user
If I refresh the page it correctly adds the user

sqlmetal.exe run and output generated but how do I query my database?

I have run sqlmetal.exe agaisnt my database.
SqlMetal.exe /server:server /database:dbname /code:mapping.cs
I have included this into my solution. So I can now create an object for each of the database tables. Great. I now wish to use ling to query by database. Can I presume that none of the connection etc is handled by the output of sqlmetal.exe. If this is correct what ways can I use ling to query my database?
Does the generated code include a Data Context (a class which inherits from System.Data.Linq.DataContext)? If so, then that's probably what you're looking for. Something like this:
var db = new SomeDataContext();
// You can also specify a connection string manually in the above constructor if you want
var records = db.SomeTable.Where(st => st.id == someValue);
// and so on...

Table with a foreign key

how can I build a table of "orders" containing "IdOrder", "Description" and "User"?... the "User" field is a reference to the table "Users", which has "IdUser" and "Name". I'm using repositories.
I have this repository:
Repository<Orders> ordersRepo = new OrderRepo<Orders>(unitOfWork.Session);
to return all Orders to View, I just do:
return View(ordersRepo.All());
But this will result in something like:
IdOrder:1 -- Description: SomeTest -- User: UserProxy123ih12i3123ih12i3uh123
-
When the expected result was:
IdOrder:1 -- Description: SomeTest -- User: Thiago.
PS: I don't know why it returns this "UserProxy123ih12i3123ih12i3uh123". In Db there is a valid value.
The View:
It is showed in a foreach (var item in Model).
#item.Description
#item.User //--> If it is #item.User.Name doesn't work.
What I have to do to put the Name on this list? May I have to do a query using LINQ - NHibernate?
Tks.
What type of ORM are you using? You mention "repositories" but does that mean LinqToSql, Entity Framework, NHibernate, or other?
It looks like you are getting an error because the User field is not loaded as part of the original query. This is likely done to reduce the size of the result set by excluding the related fields from the original query for Orders.
There are a couple of options to work around this:
Set up the repository (or context, depending on the ORM) to include the User property in the result set.
Explicitly load the User property before you access it. Note that this would be an additional round-trip to the database and should not be done in a loop.
In cases where you know that you need the User information it would make sense to ensure that this data in returned from the original query. If you are using LinqToSql take a look at the DataLoadOptions type. You can use this type to specify which relationships you want to retrieve with the query:
var options = new DataLoadOptions();
options.LoadWith<Orders>(o => o.User);
DataContext context = ...;
context.LoadOptions = options;
var query = from o in context.Orders
select o;
There should be similar methods to achive the same thing whatever ORM you are using.
In NHibernate you can do the following:
using (ISession session = SessionFactory.OpenSession())
{
var orders = session.Get<Order>(someId);
NHibernateUtil.Initialize(orders.User);
}
This will result in only two database trips (regardless of the number of orders returned). More information on this can be found here.
In asp.net MVC the foreign key doesn't work the way you are using it. I believe you have to set the user to a variable like this:
User user = #item.User;
Or you have to load the reference sometimes. I don't know why this is but in my experience if I put this line before doing something with a foreign key it works
#item.UserReference.load();
Maybe when you access item.User.Name the session is already closed so NHib cannot load appropriate user from the DB.
You can create some model and initialize it with proper values at the controller. Also you can disable lazy loading for Orders.User in your mapping.
But maybe it is an other problem. What do you have when accessing "#item.User.Name" from your View?

Resources