Affichage des articles dont le libellé est Active questions tagged database - Stack Overflow. Afficher tous les articles
Affichage des articles dont le libellé est Active questions tagged database - Stack Overflow. Afficher tous les articles

dimanche 28 juin 2015

Executing non-database actions in a transaction in Slick 3

I'm having trouble understanding the new Slick DBIOAction API, which does not seem to have a lot of examples in the docs. I am using Slick 3.0.0, and I need to execute some DB actions and also some calculations with the data received from the database, but all of those actions have to be done inside a single transaction. I'm trying to do the following:

  1. Execute a query to database (the types table).
  2. Do some aggregations and filtering of the query results (this calculation can't be done on the database).
  3. Execute another query, based on the calculations from step 2 (the messages table — due to some limitations, this query has to be in raw SQL).
  4. Join data from step 2 and 3 in memory.

I want the queries from step 1 and 3 to be executed inside a transaction, as the data from their result sets has to be consistent.

I've tried to do this in a monadic join style. Here's an overly simplified version of my code, but I can't even get it to compile:

  val compositeAction = (for {
    rawTypes <- TableQuery[DBType].result
    (projectId, types) <- rawTypes.groupBy(_.projectId).toSeq.map(group => (group._1, group._2.slice(0, 10)))
    counts <- DBIO.sequence(types.map(aType => sql"""select count(*) from messages where type_id = ${aType.id}""".as[Int]))
  } yield (projectId, types.zip(counts))).transactionally

  1. The first row of for comprehension selects the data from the types table.
  2. The second row of for comprehension is supposed to do some grouping and slicing of the results, resulting in a Seq[(Option[String], Seq[String])]
  3. The third row of for comprehension has to execute a set of queries for every element from the previous step, in particular, it has to execute a single SQL query for each of the values inside Seq[String]. So in the third row I build a sequence of DBIOActions.
  4. The yield clause zips types from the second step and counts from the third step.

This construction, however, does not work and gives two compile time errors:

Error:(129, 16) type mismatch;
 found   : slick.dbio.DBIOAction[(Option[String], Seq[(com.centreit.proto.repiso.storage.db.models.DBType#TableElementType, Vector[Int])]),slick.dbio.NoStream,slick.dbio.Effect]
    (which expands to)  slick.dbio.DBIOAction[(Option[String], Seq[(com.centreit.proto.repiso.storage.db.models.TypeModel, Vector[Int])]),slick.dbio.NoStream,slick.dbio.Effect]
 required: scala.collection.GenTraversableOnce[?]
        counts <- DBIO.sequence(types.map(aType => sql"""select count(*) from messages where type_id = ${aType.id}""".as[Int]))
               ^
Error:(128, 28) type mismatch;
 found   : Seq[Nothing]
 required: slick.dbio.DBIOAction[?,?,?]
        (projectId, types) <- rawTypes.groupBy(_.projectId).toSeq.map(group => (group._1, group._2.slice(0, 10)))
                           ^

I've tried to wrap the second line in a DBIOAction by using DBIO.successful, which is supposed to lift a constant value into the DBIOAction monad:

(projectId, types) <- DBIO.successful(rawTypes.groupBy(_.projectId).toSeq.map(group => (group._1, group._2.slice(0, 10))))

But in this code the types variable is inferred to be Any, and the code does not compile because of that.

Full Export in PHPMyAdmin Problems

So today i was switching to my new webserver and when i backed up my mysql databases a did a full export.... is there anyway to import my full.sql file and still have all the databases separate and not all in one database?

POSTGRES - Combine same columns with different text in one row

I have three tables that i want to combine. I have a table doctor, patient and operation. Doctor represents all cind of doctors. Patient represents a patient and operation holds primaryKeys from patient and doctor. How do i write a query which will show me chiefDoctor and assistantDocotor and Patient? What did i reach so far?

Show firstname and lastname from one either Chiefdoctor or Assistantdoctor. How do i write to show a table with both Chief and Assistant in it?

select a.vorname|| ' ' || a.nachname AS leitenderArzt, p.firstname || ' ' || p.lastname AS patient
from angestellter a inner join operation o on a.id = o.leitenderarzt
inner join patient p on o.patientident=p.ident

| id | firstname       | lastname      | patient      |
| 1  | ImA             | ChiefDoctor1  | p.firstname  |
| 3  | ImA             | ChiefDoctor3  | p.firstname  |

The underlying structure of my database with a representation.

CREATE TABLE doctor
(
  id serial NOT NULL,  
  firstname character varying(255) NOT NULL,
  lastname character varying(255) NOT NULL,  
  CONSTRAINT angestellter_pkey PRIMARY KEY (id),
}

 Table doctor
 |id | firstname | lastname        |
 | 1 | ImA       | ChiefDoctor1    |
 | 2 | ImA       | AssistantDoctor |
 | 3 | ImA       | ChiefDoctor2    |

CREATE TABLE patient
(
  ident serial NOT NULL,  
  firstname character varying(255) NOT NULL,
  lastname character varying(255) NOT NULL,
  CONSTRAINT patient_pkey PRIMARY KEY (ident),
}

Table patient
| ident | firstname | lastname |
| 1     | Operated  | ME       |

CREATE TABLE operation
(
  id serial NOT NULL,
  chiefDoctor integer NOT NULL,
  AssistantDoctor integer NOT NULL,
  patientident integer NOT NULL,
  CONSTRAINT operation_pkey PRIMARY KEY (id),
  CONSTRAINT fkoperation539608 FOREIGN KEY (patientident)
      REFERENCES patient (ident) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT fkoperation745809 FOREIGN KEY (assistantDoctor)
      REFERENCES angestellter (id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT fkoperation949671 FOREIGN KEY (chiefDoctor)
      REFERENCES angestellter (id) MATCH SIMPLE
}

Table operation
| id | doctorID | doctorID | patientID |
| 1  |    1     |    2     |     1     |

How do i write a query which will show show who operated a patient with full name? It should look like this.

| id | chiefdoctor       | assistantdoctor      | patient      |
|----| ImA + ChiefDoctor |ImA + AssistantDoctor | Operated + ME|

Android - In App Purchase to remove admob ad bar

I am developing an app for Google Play that will integrate an admob ad bar. I see many apps on the appstore offer in app purchases to remove ads and would like to do the same with my app.

Are there any tutorials or ways you can think of to achieve this by not using SavedPreferences or having to query with a database that I'd have to create.

I may sound lazy but I really want a solution that would query with a Google Play server rather than one I will have to create.

My reasoning is because a server I would create would take their device id and I want the in app purchase to carry across multiple devices under one Google Play account.

What are the benefits and disadvantages of various database models?

I have a general overview of several models, including relational, document-based, graph-based, object-based, key-value store, etc., but what are the advantages and disadvantages of each?

Mongoose update not working with embedded objects

I'm working in the MEAN stack, and I'm stuck on a Mongoose issue. Updates are working fine for individual documents(single key:value), but when I attempt to update a nested object with a new object, it's just deleting the original object and not inserting the new one.

Using an identical query directly in mongo, within the terminal, works perfectly. But from my Mongoose model, I get the above behavior.

My final desired query is more complicated and uses many variables, so I've simplified the code to the following to highlight the issue:

Setup.update({name: "main"}, {$set: {"schedule.sunday.eleven_pm": { associates: 111, supervisors: 111}}}, function(err){
            if(err){
                console.log(err);
            }
            else{
                console.log('successfully updated main schedule setup')
                Setup.find({}, function(err, setup){
                    if(err){
                        console.log(err);
                    }
                    else{
                        res.json(setup);
                    }
                })
            }
        });

Gives me this in my db:

"eleven_pm" : {

        }

But from terminal, the same query (cut and pasted from my mongoose query, just added 'db.setups' to beginning:

db.setups.update({name: "main"}, {$set: {"schedule.sunday.eleven_pm": { associates: 111, supervisors: 111}}})

Gives me this, the desired result:

    "eleven_pm" : {
            "associates" : 111,
            "supervisors" : 111
        }

I've tried writing this as a findOneAndUpdate(), but encountered the same behavior. Am I doing something unorthodox here?

Any help greatly appreciated.

Something wrong with my IF statement

I created a simple code for my web game, there are no errors but some part of the code does not work. Parts which do not work are last two if statements, it won't give users an Antimatter, but it prints out correct message. Why it won't update DB correctly ?

CODE:

    ///////////////////////////////BLACKBOX////////////////
function buyblackbox(){
global $USER, $PLANET, $LNG, $UNI, $CONF,$resource,$pricelist;
$blackbox = HTTP::_GP('blackbox', 0);
$price = 10000 * $blackbox;
$loli   = mt_rand(1,2);
if ($price < 0) {
$this->printMessage("Hack attempt.", true, array('game.php?page=premium', 2));
}
if($USER['antimatter'] < $price){
$this->printMessage("You do not have enough antimatter", true, array('game.php?page=premium', 2));
die();
}
elseif($blackbox < 0){
$this->printMessage("Hack attempt.", true, array('game.php?page=premium', 2));
die();
}else{
    $USER['antimatter'] -= $price;
$GLOBALS['DATABASE']->query("UPDATE ".USERS." SET `darkbox` = '".$loli."', `antimatter` = `antimatter` - '".$price."' WHERE `id` = ".$USER['id'].";");

if($USER['darkbox'] == 1)
{
$GLOBALS['DATABASE']->query("UPDATE ".USERS." SET `darkmatter` = `darkmatter` - '".$price."' WHERE `id` = ".$USER['id'].";");
$this->printMessage('vins nem sit has succesfully be bought', true, array('game.php?page=premium', 2));
}
if($USER['darkbox'] == 2)
{
$GLOBALS['DATABASE']->query("UPDATE ".USERS." SET `darkmatter` = `darkmatter` + '".$price."' WHERE `id` = ".$USER['id'].";");
$this->printMessage('BlackBox has succesfully be bought', true, array('game.php?page=premium', 2));
}
}
die();
}
/////////////////////////////////END BLACKBOX///////////////////////

Syncing data changes between devices (offline and online)

I have to create an application that has functionality similar to the contacts app. You can add a contact on the client's iPhone and it should get uploaded onto the client's iPad. If the client updates the contact on their iPad, it should get updated on their iPhone.

Most of this is fairly straight forward. I am using Parse.com as my back end and saving contacts locally with Core Data. The only problem I'm encountering is managing contacts when the user is offline.

Let's say I have an iPhone and an iPad. Both of them have the same up-to-date version of the online database. My iPhone is offline.

At 10AM I update the phone number for a contact on my iPad online. At 11AM I update the email address for the same contact on my iPhone but I'm offline.

Later that day my iPhone gets online and checks the servers for changes. It sees that all of its changes are more recent (checking an updatedAt timestamp property) and doesn't download the new phone number for the contact. Instead, it updates the properties that have changed since the older 10AM update and overrides the new phone number along with the email address.

How am I supposed to manage the online/offline problems encountered such as the one above?

I was thinking to have an updatedLocally and updatedOnline property on every object. This way if the two don't match I can do a diff-check and use the most recent one for conflicts but this doesn't seem like the cleanest solution. Has anyone else encountered this problem? If so, how did you solve it?

MS Access automation filling out forms and database tables

I have MS Access database, I need to automate filling out forms OR database tables from text file. How can I do it ?

Sql Error when running queires file

I am trying to run CREATE TABLE persons (id int(4) NOT NULL auto_increment, name varchar(30) NOT NULL, favorite_color varchar(30) NOT NULL, weight int(5) NOT NULL, favorite_movie varchar(20), state varchar(20), PRIMARY KEY (id));

I am recieving syntax error near unexpected token `('

Any help appreciated what im doing wrong.

Understanding the use of Gedmatch

I have been involved with genealogy for some time now. It is only recently that I have made strides forward to find my family and that was because of the use of various websites in Germany. About a year ago I use the Ancestry DNA option to find out what my DNA would tell me.

The initial result I got back from Ancestry was impressive and I was excited to find that there were over 15,000 people whose names I was given who were related to me. However when I started to check these people none of them had my last name which is Beucke. About four months ago I received notice that Ancestry DNA had changed and now my list dropped to 7,700 people but still no one with my last name. I have met numerous people on genealogy websites and many have told me that I should use Gedmatch to help me find valid relatives. I was not sure how Gedmatch could help me and I am still not certain that I can get any help from this website.

I accessed the Tools for DNA & Genealogy Research page and then selected Analyze Your Data and DNA Raw Data with the option One-To-Many Matches. The results I received were hard to understand. I selected three people from the list and what I received was a list of chromosomes that no match was found for. Even the ones that I did find a match for I have no idea what this means to me or to my research. If someone can explain this to me I would appreciate it.

Regards,

Garry Beucke (garry_beucke@hotmail.com)

PHP writing wrong value into DB?

I created the following table inside a DB

$sql = "CREATE TABLE tac_flightsize
(
    id int NOT NULL AUTO_INCREMENT,
    PRIMARY KEY (id),

    gameid int NOT NULL,
    shipid int,
    flightsize int
 )";

I check for a DB write like this:

if (!$ship->superheavy){
   debug::log("db flight: " + $ship->flightSize);
   self::$dbManager->submitFlightSize($id, $gamedata->id, $ship->id, $ship->flightSize);
}

The debug::log entry shows 12 as the $ship->flightSize so the value is correct.

Here is the actual submitFlightSize function:

public function submitFlightSize($shipid, $gameid, $flightSize){
        try{
            $sql = "INSERT INTO `B5CGM`.`tac_flightsize` VALUES(null, $gameid, $shipid, $flightSize)";
            $id = $this->insert($sql);
            Debug::log($sql);

        }catch(Exception $e) {
            $this->endTransaction(true);
            throw $e;
        }
}

The Debug:::log from this function shows the follow SQL entry

INSERT INTO `B5CGM`.`tac_flightsize` VALUES(null, 2535, 16238, 1) 

Now, the last parameter is 1, when it should be 12 and was a second ago according to the earlier debug.

Can anyone explain to me what i might be doing wrong ?

What is the performance difference in MySQL relational division (IN AND instead of IN OR) implementations?

Because MySQL does not have a built in relational division operator, programmers must implement their own. There are two leading examples of implementations which can be found in this answer here.

For posterity I'll list them below:

Using GROUP BY/HAVING


SELECT t.documentid
FROM TABLE t
WHERE t.termid IN (1,2,3)
GROUP BY t.documentid
HAVING COUNT(DISINCT t.termid) = 3

The caveat is that you have to use HAVING COUNT(DISTINCT because duplicates of termid being 2 for the same documentid would be a false positive. And the COUNT has to equal the number of termid values in the IN clause.

Using JOINs


SELECT t.documentid
FROM TABLE t
JOIN TABLE x ON x.termid = t.termid
              AND x.termid = 1
JOIN TABLE y ON y.termid = t.termid
              AND y.termid = 2
JOIN TABLE z ON z.termid = t.termid
              AND z.termid = 3

But this one can be a pain for handling criteria that changes a lot.

Of these two implementation techniques, which one would offer the best performance?

Avoid Duplicate values for INSERT in SQL

  <?php 
mysql_query("INSERT INTO `users_badges` (`user_id`, `badge_id`, `badge_slot`) VALUES ('$my_id', 'VIP', '1')");
?>

I have this code to insert something in the table but every time if you visit the home page the same user gets the item dubplicated. How can I fix this.

So basicilly I want IF already you have VIP,the code doesn't have a value to avoid duplicate.

Mysql sub-filtering

Let's say I have a table U of users and a table R which represents the relations (friendships) between the users. Users are able to create posts which are saved in another table P (with the user_id of the user who sent the post).

I want to retrieve all the posts made by friends of friends of friends.... of friends of a specific person. This means when e.g. I have the following setup:

users (U)
  id - name
  1 - Mark
  2 - Eve
  3 - Peter

relations (R)
  id_user1 - id_user2
  1 - 2
  2 - 3

posts (P)
  id - user_id - text
  1 - 1 - "Hello from Mark"
  2 - 2 - "Hello from Eve"
  3 - 3 - "Hello from Peter"

and I want to retrieve all messages made by Mark, i would simply select all posts with Mark's user_id. But its getting tricky when I want to retrieve all the posts made by Mark's friends. Mark has only one friend in this example, so it's kind of obvious that we would get Eve's and Mark's post here. But let's assume he has 500. I would first execute a SQL command to retrieve all his friends and then do something like

SELECT * from posts WHERE user_id in (2,4,5,6,7,8,9,10,11,12.....,1442);

Well that seems quite inefficient, but it gets even worse when I want to get the messages made by friends of his friends (or even more sub-friend layers n): I would make n requests (one for each layer) to retrieve the id's of his friend's friends like in the example above. Then, when I have the result of the Id's of his n-sub-friends, I would do the same as above. For example, when we want to retrieve all posts by Marks friend's friends, we would get all the posts because Mark's friend Eve has Peter as a friend.

When the user has only 10 friends and each friend also got 10 friends, I would get 10^n ids. When I want to create a network containing ALL the posts of "somehow connected" friends, it would take ages to only get the ID's of all the users. And I guess the filtering with " in (....) " would take even longer when I pass like 100'000 id's.

Is there an efficient way to solve this problem?

I thought about saving some redundant data like associating every single sub-friend with every user directly in another table, but I doubt that this will work well because this would become a really gigantic table..

Warning: mysqli_num_rows() using MySQL search MATCH AGAINST $keywords [duplicate]

I am testing to get results using a new to me way of searching MySQL using MATCH AGAINST

Here is the code:

<?php
$keyworkds = mysqli_real_escape_string($database,$_POST['keywords']);
$result=mysqli_query($database,"
SELECT * FROM products 
WHERE MATCH (product,manufacturer,model) 
AGAINST ('$keyworkds')");
if(mysqli_num_rows($result)>0){
while($display=mysqli_fetch_assoc($result)){?>

Product:
<?php echo $display['product'] ?>

Manufacturer:
<?php echo $display['manufacturer'] ?>

Model:
<?php echo $display['model'] ?>



<?php }?>   

<?php }else{?> 

there are no results

<?php }?>

The problem is that I get the follow error and I can not see where the problem is. Any idea?

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in /home/local/public_html/

System says the error is on line 89 the funny thing is that line 89 is empty and around it are only divs

Change default database of Bonita 6.5

I am using bonita 6.5 and I would like to change the organizational database : users , roles , tasks , permissions...(not data) of bonita to my mysql database. I've followed the official documentation but then I realised that it's maybe for data and I wonder if that's true !

1) If it's for data then how can I change the oraginzational DB ?

2) Otherwise , how can bonita "know" that I have users ... in that DB ? what are the changes that I have to make ? Thanks.

How to make a Child table to access another table laravel

I am using Laravel 5.1.

I have Three Table.

  • Films
  • Videos
  • Video Category

User can create a film and add many videos, but every video should belong to any one category (example. Making Video, Trailer Video, Film Events).

Now i want to fetch all films,video and video category of each video by passing a Film ID.

Table structure

Films Table

filmID | filmName 
-----------------
   1   |  Film 1
   2   |  Film 2

Video Table

videoID | catID | videoURL
--------------------------
   1    |  cat1 |   URL 1
   2    |  cat2 |   URL 2

Video Category Table

  catID  | category
--------------------
   cat1  |  Trailer
   cat2  |  Making
   cat3  |  Events

I can get All the Videos by passing FilmID

{
  filmId: "filmName",
  filmName: "Film Name",
  coverPhoto: "image URL",
  created_at: "2015-06-28 06:35:26",
  updated_at: "2015-06-28 06:35:45",
  videos: [
      {
        id: 7,
        filmId: "filmID",
        videoCategory: "trailer",
        videoUrl: "h41Jb29P4",
        created_at: "2015-06-28 11:40:22",
        updated_at: "2015-06-28 11:40:22"
      }
  ]
}

But how to i get the Video Category along with this output. Something like this

{
      filmId: "filmName",
      filmName: "Film Name",
      coverPhoto: "image URL",
      created_at: "2015-06-28 06:35:26",
      updated_at: "2015-06-28 06:35:45",
      videos: [
          {
            id: 7,
            filmId: "filmID",
            videoCategory: "trailer",
            videoUrl: "h41Jb29P4",
            created_at: "2015-06-28 11:40:22",
            updated_at: "2015-06-28 11:40:22"
            videoCategory: [
                  {
                     videoCategoryId: "1",
                     videoCategoryName: "Trailer"
                  }
            ]
          }
      ]
    }

Is there any way to do without passing multiple queries and merge in PHP?

Please anyone Help me.

Best practice for monitoring db table updates

I have a question 1) I have one table which will contain some rows (inserted by some other process after completing some work) 2) I need to make a process which will pick those rows, do some logic and then update an other system on REST.

Please suggest what is the best practice, Daemon or MQ? message queue? or any other best practice used for this thing.

How to record datareader results at Session?

How to record datareader results at Session? I read database then value that I read want to assigne at Session Thank you in advance for your advise

dr = islem.KayitGetir_DataReader("SELECT * FROM products P INNER JOIN products_description PD ON P.products_id = PD.products_id WHERE P.products_id='" + Session[i].ToString() + "'");

if (dr.Read())
{
    cartProductImage.ImageUrl = dr["products_thumbnails_images"].ToString();
    lblCartProductName.Text   = dr["pro_description_name"].ToString();
    lblCartProductPrice.Text  = dr["products_price"].ToString();
    dr.Close();

    Session["ProImg"]      = cartProductImage;
    Session["ProImgName"]  = lblCartProductName;
    Session["ProImgPrice"] = lblCartProductPrice;
}