Showing posts with label mysql. Show all posts
Showing posts with label mysql. Show all posts

Thursday, October 11, 2018

Hibernate saves/retrieves date minus day if application uses another timezone than MySQL

Leave a Comment

I have an application started on tomcat on MACHINE_A with timezone GMT+3.

I use remote mysql server started on MACHINE_B with timezone UTC.

We use spring-data-jpa for persistence.

As an example of the problem, I will show the repository:

public interface MyRepository extends JpaRepository<MyInstance, Long> {     Optional<MyInstance> findByDate(LocalDate localDate); } 

If I pass localDate for 2018-09-06, I get entities where the date is 2018-09-05(previous day)

In the logs I see:

2018-09-06 18:17:27.783 TRACE 13676 --- [nio-8080-exec-3] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [DATE] - [2018-09-06] 

I googled that question a lot and found a several articles with the same content(for example https://moelholm.com/2016/11/09/spring-boot-controlling-timezones-with-hibernate/)

So, I have the following application.yml:

spring:   datasource:     url: jdbc:mysql://localhost:3306/MYDB?useUnicode=true&characterEncoding=utf8&useSSL=false&useLegacyDatetimeCode=false&serverTimezone=UTC     username: root     password: *****   jpa:     hibernate:       naming:         physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl     properties:       hibernate:         show_sql: true         use_sql_comments: true         format_sql: true         type: trace         jdbc:           time_zone: UTC 

But it doesn't help.

We use the following connector:

<dependency>     <groupId>mysql</groupId>     <artifactId>mysql-connector-java</artifactId>     <version>8.0.12</version> </dependency> 

How can I resolve my problem?

P.S.

I tried to run both applications with the same time zone. In this case everything works as expected.

P.S.2

I tried to use mysql driver 6.0.6 version but it doesn't change anything.

6 Answers

Answers 1

If you're using LocalDate in Java, you should use a DATE column in MySQL. This way the problem will be solved.

If you use LocalDateTime, try setting the property like this in Spring Boot:

spring.jpa.properties.hibernate.jdbc.time_zone=UTC 

For a more detailed explanation, check out this article. You can find a test case in my High-Performance Java Persistence GitHub repository which works just fine.

Answers 2

Ideally, your both servers should be in same time zone and preferred one be in UTC time zone. And to show correct time to user in his timezone; you parse it in browser itself. And while retrieving data from DB; you use UTC time. This way you will not have issue while fetching data from DB

Answers 3

In MySQL...

TIMESTAMP internally stores UTC, but converts to/from the server's timezone based on two settings. Check those settings via SHOW VARIABLES LIKE '%zone%'; Properly configured, the reader may see a different time than the writer (based on tz settings).

DATE and DATETIME take whatever you give it. There is no tz conversion between the string in the client and what is stored in the table. Think of it a storing a picture of a clock. The reader will see the same time string that the writer wrote.

Answers 4

I faced similar issues while creating some integration tests for a spring-boot application using hibernate. The database I used here was postgreSQL.

As another answer correctly points out, you can set the hibernate.jdbc.time_zone=UTC property like discribed. Nevermind this didn't solve my issues, so I had to set the JVM default time zone with the help of the following in my spring-boot applications main class:

@PostConstruct public void init(){     TimeZone.setDefault(TimeZone.getTimeZone("UTC"));   // It will set UTC timezone     System.out.println("Spring boot application running in UTC timezone :"+new Date());   // It will print UTC timezone } 

This should also solve your problems. You can gather more informations here.

Reason

I guess your problem (retrieving date - 1 day) comes from your specific setup. If your application is running in UTC and requesting timestamps from a database in GMT+3 it resolves in a earlier date, because the applications context (JVM and Hibernate are responsible here) is 3 hours behind the database context in UTC. Simple example:

2018-12-02 00:00:00 - 3hours = 2018-12-01 21:00:00

As you are only looking to the dates: 2018-12-02 - 3hours = 2018-12-01

Answers 5

spring.jpa.properties.hibernate.jdbc.time_zone=UTC

It's used when you are working TimeZoned Date, but from your logs it seems you are not passing TimeZone:

binding parameter [1] as [DATE] - [2018-09-06]

Try to remote property:

spring.jpa.properties.hibernate.jdbc.time_zone=UTC

Answers 6

If you add the following parsing to your HQL query, it will return a date without any time zone format or time of day. This is a quick workaround to your issue.

select DATE_FORMAT(date,'%Y-%m-%d') from Entity 
Read More

Wednesday, October 3, 2018

Prevent Sending Duplicate record from MySQL and PHP

Leave a Comment

I have one table as ad_banner_queue which is i am using to generate the Queue based on weightage of ads. Ads are inserted into advertisement table. Queue will be generated if all existing ads which are in queue delivered to user.

Now the issue is how should i prevent to sending the duplicate ads in case of request came at same time and Rand() returned the same record?

Below is the Code:

<?php /* To Get the random Ad */ public function getBanner($params) {     /* Fetch the Random from table */     $ads_queue = (new \yii\db\Query())             ->select('ad_quque_id, banner_image, unique_code')             ->from('ad_banner_queue')             ->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id')             ->where('is_sent=0')             ->orderBy('RAND()')             ->one();      /* In case of queue is not there generate the new queue */     if ($ads_queue === false) {         $output = $this->generateAdQueue();         //In case of something went wrong while generating the queue         if ($output == false) {             return array();         }          //Now fetch the record again         $ads_queue = (new \yii\db\Query())                 ->select('ad_quque_id, banner_image, unique_code')                 ->from('ad_banner_queue')                 ->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id')                 ->where('is_sent=0')                 ->orderBy('RAND()')                 ->one();     }      /* Now, marked that one as is_sent */     Yii::$app->db->createCommand()->update('ad_banner_queue', ['is_sent' => 1], 'ad_quque_id =:ad_quque_id', array(':ad_quque_id' => $ads_queue['ad_quque_id']))->execute();     return $ads_queue; }  /**  * Below will Generate the Queue if not exist  */ public function generateAdQueue() {     /* First check thatt there is existing queue, if so don't generate it */     $data_exist = (new \yii\db\Query())             ->select('ad_quque_id')             ->from('ad_banner_queue')             ->where('is_sent=0')             ->scalar();     if ($data_exist === false) {         /* Delete all other entries */         (new \yii\db\Query())                 ->createCommand()                 ->delete('ad_banner_queue')                 ->execute();          /* Fetch all banner */         $ads = (new \yii\db\Query())                 ->select('ad_id, unique_code, ad_name, banner_image,ad_delivery_weightage')                 ->from('advertisement')                 ->where('status_id in (8)') //Means only fetch Approved ads                 ->all();         if (!empty($ads)) {             foreach ($ads as $ad) {                 /* Make entry as per that weightage, example, if weightage is 10 then make entry 10 times */                 $ins_fields = array();                 for ($i = 1; $i <= $ad['ad_delivery_weightage']; $i++) {                     $ins_fields[] = array($ad['ad_id']);                 }                 Yii::$app->db->createCommand()->batchInsert('ad_banner_queue', ['ad_id'], $ins_fields)->execute();             }             return true;         } else {             return false;         }     } else {         return false;     } } 

7 Answers

Answers 1

I'm taking it that you mean that different "people" that are conducting simultaneous requests should not get the same random row? The most robust way, without testing it, in order to avoid the minute chance of the same record being selected twice in two running requests will probably be to lock the table and perform the read and update in a transaction. You would have to use a storage engine that supports this, such as InnoDB.

The way to accomplish LOCK TABLES and UNLOCK TABLES with transactional tables, such as InnoDB tables, is to begin a transaction with SET autocommit = 0, not START TRANSACTION, followed by LOCK TABLES. Then you should not call UNLOCK TABLES until you commit the transaction explicitly.

For example, if you need to read and write to your table in one go, you can do this:

SET autocommit = 0; LOCK TABLES ad_banner_queue AS ad_banner_queue_w WRITE, ad_banner_queue AS ad_banner_queue_r READ; ... perform your select query on ad_banner_queue_r, then update that row in ad_banner_queue_w with is_sent = 1... COMMIT; UNLOCK TABLES; 

The reason we lock with an alias is that you cannot refer to a locked table multiple times in a single query using the same name. So we use aliases instead and obtain a separate lock for the table and each alias.

Answers 2

Although it might seem to be a trivial question it is not at all, there are several ways to handle it and each of them has its own downsides, mainly you can face this issue from three different points:

Live with it

Chances you can get a repeated pull are low in real life and you need to really think if you are willing to face the extra work just to make sure an ad is not shown twice in a row, you also need to think caches exist and you might break your brain making ads atomic just to find out browser/proxy/cache are serving a repeated ad :(

Handle it on database

You can handle this issue leaving the database the responsability to keep data safe and coherent(indeed it is the main task of database), there are several ways of doing it:

  • Locks and table (as previously suggested), I personally disklike the approach of using locks with PHP and MySQL, you will suffer performance penalities and risk deadlocking but anyway it's still a solution, you just make a select for update on your queue table to be sure no-one reads again until you update. The problem in here is you will lock the whole table while this is done and you need to be careful with your DB Driver and autocommits.
  • Cursors Cursors are database structures created basically for the duty you are willing to do, you create a cursor and safely traverse it with its functions. Using cursors into PHP might be very tricky due to transactions too and you need to know very well what are you doing to avoid errors.
  • Cursors and stored procedures the best way to handle this into database is managing cursors inside the database itself, that's why stored procedures are there, just create procedures to pull a new item from your cursor and to fill it again once it's all consumed.

Handle it on PHP side

In this case you need to implement your own queue on PHP and there might be several ways to do so but the main problem might be implementing multiprocess-safe atomic operations on your app, I personally dislike using any kind of locks if you are not 100% sure of the execution flow of your app or you might end up locking it all. Anyway there are three chances in here:

  • Use sems or mutex both included on php or third party, timeouts and locks can become a hell and they are not easy to detect so as stated above I'd avoid it.

  • Use PHP MSG Queue I think this is the safest way as long as you run your app on a *nix system, just send all the available ads to the message queue instead of creating a table on database, once all ads are consumed you can regenerate the queue once again, the drawback of this system is your server can not be distributed and you might lose the current queue status if you don't save it before a restart.

  • Third party queue system depending on your app workload or interactions you might need to use a queue management system, this is a must if you want a distributed system, it might sound too serious using a msg queue system to handle this issue but this kind of approaches may be life-savers.

Summary

If you can't live with it and are proficient enough with databases i'd go for stored procedures and cursors, you don't need to break your mind with concurrency, database will handle it as long as you are using an ACID compliant database (not MyISAM i.e.)

If you want to avoid conding into the database and your system is *nix and not going to be distributed you can give a try to msg_queues

If you think your system may be sometime distributed or do not rely on old SysV mechanisms you can give a try to a message broker like RabbitMQ, this nice things are addictive and once you start using them you start seeing new uses for them daily.

Answers 3

You may use mutex component to ensure that there is only one process trying to pop ad from queue.

$banner = []; $key = __CLASS__ . '::generateAdQueue()' . serialize($params); if (Yii::$app->mutex->acquire($key, 1)) {     $banner = $this->getBanner($params);     Yii::$app->mutex->release($key); } 

However be aware that this may greatly reduce performance, especially if you want to process multiple request at the same time. You may consider different technology for such queue, relational databases does not really fit well for such task. Using Redis-based queue and SPOP may be much better choice.

Answers 4

Presumably, the ads are presented from separate pages. HTML is "stateless", so you cannot expect one page to know what ads have previously been displayed. So, you have to either pass this info from page to page, or store it somewhere in the database associated with the individual user.

You also want some randomizing? Let's do both things at the same time.

What is the "state"? There is an "initial state", at which time you randomly pick the first ad to display. And you pass that info on to the next page (in the url or in a cookie or in the database).

The other "state" looks at the previous state and computes which ad to display next. (Eventually, you need to worry about running out of ads -- will you start over? Will you re-randomize? Etc.)

But how to avoid showing the same "random" ad twice in a row?

  • You have N ads -- SELECT COUNT(*) ...
  • You picked add number J as the first ad to display -- simple application of RAND(), either in SQL or in the app.
  • Pick a number, M, such that M and N are "relatively prime".
  • The "next" ad is number (J := (J + M) mod N). This will cycle through all the ads without duplicating until all have been shown. -- Again, this can be done in SQL or in the ap.
  • Pass J and M from one page to the next.

To get the J'th row: Either have the rows uniquely and consecutively numbered; or use ORDER BY ... LIMIT 1 OFFSET J. (Caveat: it may be tricky to fill J into the SQL.)

No table locks, no mutexes, just passing info from one page to the next.

Answers 5

You should create a separate db table and mark ads that user received with its help. Before sending ads to user check if he has already received it.

Answers 6

You can use transactions and SELECT FOR UPDATE construction for lock data and consistent executing of queries. For instance:

public function getAds() {     $db = Yii::$app->db;     $transaction = $db->beginTransaction(Transaction::REPEATABLE_READ);     try {         $ads_queue = (new \yii\db\Query())             ->select('ad_quque_id, banner_image, unique_code')             ->from('ad_banner_queue')             ->join('inner join', 'advertisement', 'ad_banner_queue.ad_id = advertisement.ad_id')             ->where(new Expression('is_sent=0 FOR UPDATE'))             ->orderBy('RAND()')             ->one();         if ($ads_queue === false) {             $transaction->commit();             return null;         }         $db->createCommand()->update('ad_banner_queue', ['is_sent' => 1], 'ad_quque_id =:ad_quque_id', array(':ad_quque_id' => $ads_queue['ad_quque_id']))->execute();               $transaction->commit();         return $ads_queue;     } catch(Exception $e) {         $transaction->rollBack();         throw $e;     } }  public function getBanner($params) {     $ads_queue = $this->getAds();     if (is_null($ads_queue)) {         $output = $this->generateAdQueue();                 if ($output == false) {             return array();         }         $ads_queue = $this->getAds();     }     return $ads_queue; } 

Answers 7

Make your index unique or make a check that checks the data and see's if it is a duplicate.

Hope this helps. Good luck

Read More

Tuesday, September 18, 2018

How to use “on update CURRENT_TIMESTAMP” in H2 database?

Leave a Comment

I want my entity to have a modification timestamp whenever it is updated. mysql supports this using the following definition:

@Entity public class MyTable {     @Column(columnDefinition = "TIMESTAMP default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP")     private LocalDateTime thetime; } 

Problem: in my JUnit tests I want to use an embedded inmemory H2 database. And H2 does not support on update CURRENT_TIMESTAMP.

Question: how can I keep the column definition (as I will be running mysql in all cases except in automated tests)? And how can I workaround that in my h2 testing?

1 Answers

Answers 1

The official statement from the H2 people is that it is not supported and the workaround is to create a trigger. You can read this here https://github.com/commandos59/h2database/issues/491

Whatever you put in the "columnDefinition" it is provider specific. And since you have already mapped your entity with this specific column definition you are not leaving yourself much space to manouver.

There are several things you can do. Some of the things are hacks.

  1. Mix XML configuration for the tests. The XML configurationn of the Entities has higher priority than the annotations so you can actualy override the

    @Column(columnDefinition = "TIMESTAMP default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP") private LocalDateTime thetime

with H2 specific column definition.

  1. Another alternative agnostic of the Database is to leave your time generation to the application server layer and hook it to the @PrePersist @PreUpdate listeners on the entity

  2. If you insist to have your timestamp generated by the database you can do something similar to how the IDs are generated. Have some sort of dedicated object that reads the CURRENT_TIMESTAMP from the database and puts it the entty right before you persist, update.

Read More

Saturday, September 15, 2018

Hibernate saves/retrieves date minus day if application uses another timezone than MySQL

Leave a Comment

I have application started on tomcat on MACHINE_A with timzone GMT+3

I use remote mysql server started on MASHINE_B with time zone UTC.

We use spring-data-jpa for pesistence.

As example of problem I will demonstrate repository:

    public interface MyRepository extends JpaRepository<MyInstance, Long> {         Optional<MyInstance> findByDate(LocalDate localDate); } 

if I pass localDate for 2018-09-06 I get entities where date is 2018-09-05(previous day)

In logs I see:

2018-09-06 18:17:27.783 TRACE 13676 --- [nio-8080-exec-3] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [DATE] - [2018-09-06] 

I googled that question a lot and found a several articles with the same content(for example https://moelholm.com/2016/11/09/spring-boot-controlling-timezones-with-hibernate/)

So I have following application.yml:

spring:   datasource:     url: jdbc:mysql://localhost:3306/MYDB?useUnicode=true&characterEncoding=utf8&useSSL=false&useLegacyDatetimeCode=false&serverTimezone=UTC     username: root     password: *****   jpa:     hibernate:       naming:         physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl     properties:       hibernate:         show_sql: true         use_sql_comments: true         format_sql: true         type: trace         jdbc:           time_zone: UTC 

But it doesn't help anyway.

We use following connector:

<dependency>     <groupId>mysql</groupId>     <artifactId>mysql-connector-java</artifactId>     <version>8.0.12</version> </dependency> 

How can I resolve my problem?

P.S.

I tried to run both applications with the same timezone. At this case averything works as expected

4 Answers

Answers 1

If you're using LocalDate in Java, you should use a DATE column in MySQL. This way the problem will be solved.

If you use LocalDateTime, try setting the property like this in Spring Boot:

spring.jpa.properties.hibernate.jdbc.time_zone=UTC 

For a more detailed explanation, check out this article. You can find a test case in my High-Performance Java Persistence GitHub repository which works just fine.

Answers 2

Ideally, your both servers should be in same time zone and preferred one be in UTC time zone. And to show correct time to user in his timezone; you parse it in browser itself. And while retrieving data from DB; you use UTC time. This way you will not have issue while fetching data from DB

Answers 3

In MySQL...

TIMESTAMP internally stores UTC, but converts to/from the server's timezone based on two settings. Check those settings via SHOW VARIABLES LIKE '%zone%'; Properly configured, the reader may see a different time than the writer (based on tz settings).

DATE and DATETIME take whatever you give it. There is no tz conversion between the string in the client and what is stored in the table. Think of it a storing a picture of a clock. The reader will see the same time string that the writer wrote.

Answers 4

I faced similar issues while creating some integration tests for a spring-boot application using hibernate. The database I used here was postgreSQL.

As another answer correctly points out, you can set the hibernate.jdbc.time_zone=UTC property like discribed. Nevermind this didn't solve my issues, so I had to set the JVM default time zone with the help of the following in my spring-boot applications main class:

@PostConstruct public void init(){     TimeZone.setDefault(TimeZone.getTimeZone("UTC"));   // It will set UTC timezone     System.out.println("Spring boot application running in UTC timezone :"+new Date());   // It will print UTC timezone } 

This should also solve your problems. You can gather more informations here.

Reason

I guess your problem (retrieving date - 1 day) comes from your specific setup. If your application is running in UTC and requesting timestamps from a database in GMT+3 it resolves in a earlier date, because the applications context (JVM and Hibernate are responsible here) is 3 hours behind the database context in UTC. Simple example:

2018-12-02 00:00:00 - 3hours = 2018-12-01 21:00:00

As you are only looking to the dates: 2018-12-02 - 3hours = 2018-12-01

Read More

Friday, August 31, 2018

Docker-compose check if mysql connection is ready

Leave a Comment

I am trying to make sure that my app container does not run migrations / start until the db container is started and READY TO accept connections.

So I decided to use the healthcheck and depends on option in docker compose file v2.

In the app, I have the following

app:     ...     depends_on:       db:       condition: service_healthy 

The db on the other hand has the following healthcheck

db:   ...   healthcheck:     test: TEST_GOES_HERE     timeout: 20s     retries: 10 

I have tried a couple of approaches like :

  1. making sure the db DIR is created test: ["CMD", "test -f var/lib/mysql/db"]
  2. Getting the mysql version: test: ["CMD", "echo 'SELECT version();'| mysql"]
  3. Ping the admin (marks the db container as healthy but does not seem to be a valid test) test: ["CMD", "mysqladmin" ,"ping", "-h", "localhost"]

Does anyone have a solution to this?

4 Answers

Answers 1

version: "2.1" services:     api:         build: .         container_name: api         ports:             - "8080:8080"         depends_on:             db:                 condition: service_healthy     db:         container_name: db         image: mysql         ports:             - "3306"         environment:             MYSQL_ALLOW_EMPTY_PASSWORD: "yes"             MYSQL_USER: "user"             MYSQL_PASSWORD: "password"             MYSQL_DATABASE: "database"         healthcheck:             test: ["CMD", "mysqladmin" ,"ping", "-h", "localhost"]             timeout: 20s             retries: 10 

The api container will not start until the db container is healthy (basically until mysqladmin is up and accepting connections.)

Answers 2

If you can change the container to wait for mysql to be ready do it.

If you don't have the control of the container that you want to connect the database to, you can try to wait for the specific port.

For that purpose, I'm using a small script to wait for a specific port exposed by another container.

In this example, myserver will wait for port 3306 of mydb container to be reachable.

# Your database mydb:   image: mysql   ports:     - "3306:3306"   volumes:     - yourDataDir:/var/lib/mysql  # Your server myserver:   image: myserver   ports:     - "....:...."   entrypoint: ./wait-for-it.sh mydb:3306 -- ./yourEntryPoint.sh 

You can find the script wait-for-it documentation here

Answers 3

I modified the docker-compose.yml as per the following example and it worked.

  mysql:     image: mysql:5.6     ports:       - "3306:3306"     volumes:              # Preload files for data       - ../schemaAndSeedData:/docker-entrypoint-initdb.d     environment:       MYSQL_ROOT_PASSWORD: rootPass       MYSQL_DATABASE: DefaultDB       MYSQL_USER: usr       MYSQL_PASSWORD: usr     healthcheck:       test:  mysql --user=root --password=rootPass -e 'Design your own check script ' LastSchema 

In my case ../schemaAndSeedData contains multiple schema and data seeding sql files. Design your own check script can be similar to following select * from LastSchema.LastDBInsert.

While web dependent container code was

depends_on:   mysql:     condition: service_healthy 

Answers 4

Hi for a simple healthcheck, I used:

/usr/bin/mysql --user=root --password=rootpasswd --execute \"SHOW DATABASES;\" 

Basically it runs a simple mysql command SHOW DATABASES; using as an example the user root with the password rootpasswd in the database.

If the command succeed the db is up and ready so the healthcheck path. You can use interval so it tests at interval.

Removing the other field for visibility, here is what it would look like in your docker-compose.yaml.

version: '2.1'    services:     db:       ...       healthcheck:         test: "/usr/bin/mysql --user=root --password=rootpasswd --execute \"SHOW DATABASES;\""         interval: 2s         timeout: 20s         retries: 10       app:        ...        depends_on:          db:          condition: service_healthy 
Read More

Tuesday, August 28, 2018

MySQL InnoDB Full text search containing email address

Leave a Comment

I have mysql community 5.6.13 on 2 mac laptops - one with os x 10.8 and another with os x 10.9.

As far as I can tell, the installations of mysql are the same but the same full text search behaves differently on each installation.

The query I have is:

SELECT legal_matter.* FROM legal_matter  left join user_account  on user_account.id = legal_matter.lawyer_id  left join client_account  on client_account.id = legal_matter.client_account_id  WHERE MATCH (legal_matter.question) AGAINST ('lawyer@domain.com.au' IN BOOLEAN MODE)  OR user_account.username like '%lawyer@domain.com.au%'  OR legal_matter.display_name like '%lawyer@domain.com.au%'  OR client_account.company_name like '%lawyer@domain.com.au%'  

On the laptop with 10.8, the query executes normally, on the laptop with 10.9, the query complains:

Error Code: 1064. syntax error, unexpected '@', expecting $end  

TI have no idea if it has anything to do with the different OS versions, I suspect not but am at a loss as to what the issue is.

Any pointers gratefully received.

Thanks.

4 Answers

Answers 1

I had queries that used match against email which started failing when I switched to innodb since @ is used to search for words a certain distance apart in InnoDB:

SELECT username FROM users WHERE MATCH(user_email) AGAINST('test@user.com' IN BOOLEAN MODE); ERROR 1064 (42000): syntax error, unexpected '@', expecting $end  SELECT username FROM users WHERE MATCH(user_email) AGAINST("test@user.com" IN BOOLEAN MODE); ERROR 1064 (42000): syntax error, unexpected '@', expecting $end mysql> 

Try wrapping your email address like this:

SELECT username FROM users WHERE MATCH(user_email) AGAINST('"test@user.com"' IN BOOLEAN MODE); 

or escaped:

SELECT username FROM users WHERE MATCH(user_email) AGAINST('\"test@user.com\"' IN BOOLEAN MODE); 

Answers 2

The @ symbol is an operator and conflicts with the BOOLEAN SEARCH... it shouldn't... its a bug.

This post, points that is more likely to be a problem of InnoDB and MyISAM...

https://bugs.mysql.com/bug.php?id=74042

Maybe, you had MyISAM on one machine's DB... dunno.

Answers 3

What is the context? mysql commandline tool? shell script? Java? PHP? Other? I suspect that the answer to this will lead to what changed.

Quite possibly preceding @ by \ will fix it. And that fix may work in both OSs.

Do you know if the complaint is about the @ in the AGAINST? Or all of the @? Try replacing the @ in AGAINST with a space.

Then, since 'lawyer' and 'domain' may not be next to each other, it may be necessary to say

MATCH(question) AGAINST('+lawyer +domain +com +au' IN BOOLEAN MODE)   AND question LIKE     '%lawyer@domain.com.au%'` 

FT gives you the performance; LIKE double checks that result.

Caveat: Unless you have the min token size set to 2, +au will cause lead to zero hits. One workaround is to not use the + on any 'word' shorter than the min token size. (The LIKE covers you.)

Answers 4

Try to use this syntax :

SELECT legal_matter.* FROM legal_matter  left join user_account  on user_account.id = legal_matter.lawyer_id  left join client_account  on client_account.id = legal_matter.client_account_id  WHERE MATCH (legal_matter.question) AGAINST ('+lawyer@domain.com.au' IN BOOLEAN MODE)  OR user_account.username like '%lawyer@domain.com.au%'  OR legal_matter.display_name like '%lawyer@domain.com.au%'  OR client_account.company_name like '%lawyer@domain.com.au%'  
Read More

Sunday, August 19, 2018

Mysql Group By Levels ranking

Leave a Comment
rank    points  player_id   quiz_id  1       88        1          40  2       80        3          40  3       30        3          41  4       20        1          41 

Getting this output from the following query:

SELECT m.rank,        m.scorer AS points,        m.player_id FROM   ( SELECT d.player_id,            d.scorer, @rownum := @rownum + 1 AS rank    FROM      ( SELECT t.player_id,               SUM(t.score) AS scorer       FROM answers t       JOIN PROFILE ON profile.player_id = t.player_id       JOIN quiz ON t.quiz_id = quiz.id       WHERE t.is_active = 1         AND quiz.contest_id = 1         AND profile.signin_source_id != 1         AND profile.is_active = 1         AND t.quiz_id IN (1,                           2)       GROUP BY t.player_id       ORDER BY scorer DESC, t.created_utc ASC) d,       (SELECT @rownum := 0) r) m WHERE m.scorer > 0 

However, the output I want is rank for each level separated out.

rank    points  player_id   quiz_id  1       88        1          40  2       80        3          40  1       30        3          41  2       20        1          41 

I followed these :

How to perform grouped ranking in MySQL

https://blog.sqlauthority.com/2014/03/09/mysql-reset-row-number-for-each-group-partition-by-row-number/

But can't get the desired output. Any suggestion or help is appreciated.

3 Answers

Answers 1

Try this query, it is simplier IMO:

select @quiz_id_lag := 0, @rank := 1;  select rank, points, player_id, quiz_id from (   select points,          player_id,          case when @quiz_id_lag = quiz_id then @rank := @rank + 1 else @rank := 1 end rank,          @quiz_id_lag,          @quiz_id_lag := quiz_id,          quiz_id   from tbl   order by quiz_id, points desc ) a; 

To incorporate this in your query, try:

SELECT @quiz_id_lag := 0, @rank := 1;  SELECT rank,        scorer AS points,        player_id FROM (     SELECT quiz_id,            player_id,            scorer,            CASE WHEN @quiz_id_lag = quiz_id THEN @rank := @rank + 1 ELSE @rank := 1 END rank,            @quiz_id_lag := quiz_id,            quiz_id     FROM (           SELECT t.player_id,                 SUM(t.score) AS scorer,                 t.quiz_id          FROM answers t          JOIN PROFILE ON profile.player_id = t.player_id          JOIN quiz ON t.quiz_id = quiz.id          WHERE t.is_active = 1 AND quiz.contest_id = 1 AND profile.signin_source_id != 1            AND profile.is_active = 1 AND t.quiz_id IN (1, 2)         GROUP BY t.player_id     ) d     WHERE scorer > 0     ORDER BY quiz_id, scorer DESC ) m 

Answers 2

Finally got the desired result, ending up with the query, in order to get proper ranking for level wise:

SELECT m.rank,m.scorer AS points,m.player_id, m.quiz_id  FROM (  SELECT d.player_id,d.scorer,      @rownum:= CASE WHEN @quiz_id <> d.quiz_id THEN 1 ELSE @rownum+1 END as rank,      @quiz_id:= d.quiz_id as quiz_id FROM      (SELECT @rownum := 1) r,     (SELECT @quiz_id := 0) c,(     SELECT t.player_id,SUM(t.score) as scorer, t.quiz_id      FROM answers t JOIN profile ON      profile.player_id = t.player_id     JOIN quiz ON t.quiz_id = quiz.id     WHERE t.is_active = 1 AND quiz.contest_id = 2 AND       profile.signin_source_id != 1 AND profile.is_active = 1      GROUP BY t.player_id,t.quiz_id       ORDER BY quiz_id DESC,scorer DESC, t.created_utc ASC) d    ) m  WHERE m.scorer > 0 ORDER BY quiz_id 

This will give the entire result set for all the levels for a specific group, if want to get the rank for specific levels from a specific group, then do add

AND t.quiz_id IN (1,2)   

Thanks to all who ever participated!

Answers 3

Try this

SELECT m.rank,m.scorer AS points,m.player_id, m.quiz_id  FROM (     SELECT d.player_id,d.quiz_id, d.scorer,       @cur:= IF(quiz_id=@id, @cur+1, 1) AS rank,      @id := quiz_id      FROM (             SELECT t.player_id, quiz.id as quiz_id, SUM(t.score) as scorer             FROM answers t JOIN profile ON profile.player_id = t.player_id                     JOIN quiz ON t.quiz_id = quize.id               WHERE t.is_active = 1 AND quiz.contest_id = 1                     AND profile.signin_source_id != 1 AND profile.is_active = 1                     AND t.quiz_id IN (1,2)              GROUP BY t.player_id, quiz.id              ORDER BY scorer DESC     ) d, (SELECT @id:=(SELECT MIN(id) FROM quiz), @cur:=0) AS init     order by d.quiz_id, d.scorer desc) m  WHERE m.scorer > 0 
Read More

Wednesday, August 8, 2018

Error: Handshake inactivity timeout in Node.js MYSQL module

Leave a Comment

I'm using node-mysql and most of the queries. Working. some queries not working. I tried every version of Node (from 0.5...) until (5.6.0), I also tried (4.0) and (4.1), Nothing helps.

I tried to change maually, and didn't work. I tried to change the sequence file to: this._idleTimeout = -1; and didn't help.

I read the issues and GitHub, and nothing helped.

I can try to fix it by myself, but I need more information. Where is the timeout, why? when? what is this type of message? Where is the timeout came from?

MYSQL_ERROR     { [Error: Handshake inactivity timeout]   code: 'PROTOCOL_SEQUENCE_TIMEOUT',   fatal: true,    timeout: 10000 }   

1 Answers

Answers 1

Ok, the timeout comes from the Protocol.js file line:162. If you checkout node-mysql you'll see that it is a variable "timeout" for queries. If you set the timeout to something a lot higher than 10000, the default, then the error should go away. An example is

pool = require('mysql').createPool({     connectionLimit : 1000,     connectTimeout  : 60 * 60 * 1000,     aquireTimeout   : 60 * 60 * 1000,     timeout         : 60 * 60 * 1000,     host            : process.env.DB_HOST,     user            : process.env.DB_USERNAME,     password        : process.env.DB_PASSWORD,     database        : process.env.DB_DATABASE }); 

You can also edit the timeout in the Sequence.js file (node_modules/mysql/lib/protocol/sequence/Sequence.js)

this._timeout = 100000;

Read More

Sunday, July 29, 2018

Laravel: How to update the MySQL by Eloquent in child process?

Leave a Comment

I write a Laravel Command, and it will fork some child process. Child process will update the DB by Eloquent.

Code:

<?php  namespace App\Console\Commands;  use App\Console\BaseCommand; use App\Item; use Illuminate\Console\Command;  class Test extends Command {     /**      * The name and signature of the console command.      *      * @var string      */     protected $signature = 'test';      /**      * The console command description.      *      * @var string      */     protected $description = 'Command description';      /**      * Create a new command instance.      *      * @return void      */     public function __construct()     {         parent::__construct();     }      /**      * Execute the console command.      *      * @return mixed      */     public function handle()     {         Item::first();         $children = [];         for($i = 0; $i < 5; $i++) {             $pid = pcntl_fork();             if ($pid == -1) {                 die('pmap fork error');             } else {                 if ($pid) {                     $children[] = $pid;                 } else {                     Item::first(); exit;                 }             }         }         foreach ($children as $child) {             pcntl_waitpid($child, $status);         }     } } 

Run my code:

vagrant@homestead:~/ECAME$ php artisan test     [Illuminate\Database\QueryException]   Packets out of order. Expected 1 received 116. Packet size=6255201 (SQL: select * from `items` where `items`.`deleted_at` is null limit 1)      [Illuminate\Database\QueryException]   Packets out of order. Expected 1 received 100. Packet size=6238815 (SQL: select * from `items` where `items`.`deleted_at` is null limit 1)      [Illuminate\Database\QueryException]   Packets out of order. Expected 1 received 0. Packet size=2816 (SQL: select * from `items` where `items`.`deleted_at` is null limit 1)      [Illuminate\Database\QueryException]   Packets out of order. Expected 1 received 116. Packet size=6381412 (SQL: select * from `items` where `items`.`deleted_at` is null limit 1)      [ErrorException]   Packets out of order. Expected 1 received 100. Packet size=6238815      [ErrorException]   Packets out of order. Expected 1 received 116. Packet size=6381412      [ErrorException]   Packets out of order. Expected 1 received 116. Packet size=6255201      [ErrorException]   Packets out of order. Expected 1 received 0. Packet size=2816 

What's the reason behind that? And How to update the MySQL by Eloquent in child process?

PS:

I think the reason for that problem is, all child processes use the same MySQL connection which forked from the parent process.

If I don't call Item::first() in the parent process before call fork(), it works well. (In my real use case, I can't do that... The parent process will do a lot with MySQL before fork child process.)

Because in that case, the MySQL connection doesn't initialize in the parent process, so every child process will initialize a connection on their own.

So, if it's the case, how to initialize a new MySQL connection for each child process after forked?

2 Answers

Answers 1

Since it's all about the connection dying, you can solve this by simply reconnecting to the database.

use Illuminate\Support\Facades\DB;  [...]  public function handle() {     User::first();      $children = [];      for ($i = 0; $i < 5; $i++)      {         $pid = pcntl_fork();          if ($pid == -1)          {             die('pmap fork error');         }          else          {             if ($pid)              {                 $children[] = $pid;             }              else             {                 DB::connection()->reconnect(); // <----- add this                 User::first(); exit;             }         }     }      foreach ($children as $child)      {         pcntl_waitpid($child, $status);     } } 

I tested this in Laravel 5.6 and it works.

Answers 2

And if you define a second ddbb with equal parameters in your database.php , and you launch your Item::first based in the second connection ?

# Primary database connection             'mysql' => [                 'driver'    => 'mysql',                 'host'      => 'localhost',                 'database'  => 'myddbb',                 'username'  => 'root',                 'password'  => '',                 'charset'   => 'utf8',                 'collation' => 'utf8_unicode_ci',                 'prefix'    => '',             ],   # Secondary database connection         'mysql_forConnectChildren' => [             'driver'    => 'mysql',             'host'      => 'localhost',             'database'  => 'myddbb',             'username'  => 'root',             'password'  => '',             'charset'   => 'utf8',             'collation' => 'utf8_unicode_ci',             'prefix'    => '',         ], 

Later

 $item = \DB::connection('mysql_forConnectChildren')->select('select * from Item')->get(1); 

I not tested but i think can works

Read More

Thursday, July 19, 2018

Best JPA entity model for Hashtags

Leave a Comment

I need to design a JPA entity model for hashtags in my application similar to Instagram, twitter and Stack Overflow. My application. The following are the schema specific points that our application uses

  • Hashtag should be belongs to a question
  • Hashtag is user specific.
  • Each user can tag their question with same hashtag

Currently, I have two JPA model for the above schema

Common tables applicable for both models

table: questions

columns: id, question, description, etc.,

table: users

columns: id, name, role, group, etc.,

Model 1

table: question_hash_tags

columns: id, question_id, user_id, hashtag_text

Model 2

table: hashtags

columns: id, hastag_text

table: user_hashtags

columns: user_id, hashtag_id, question_id

Model 1 will have each row even if hashtag is same between users.

Model 2 will have unique hashtag row and it is reffered across users using user_hashtags.

I am expecting a better and standard model beyond these two.

Note: Questions are searchable based on hashtags as well as users

2 Answers

Answers 1

We have three "things" here: Users, Questions, and Hashtags. I'd avoid model #1 in your example mainly because it's not flexible. What happens when the product owner later decides to add a description to tags? What happens if the product owner next week wants a user to only choose tags from an existing pool? While your domain requirements are incomplete and unclear, a more flexible solution allows for implementing future functionality on top of your model without major refactoring. With that said, I would definitely consider Hashtag to be its own independent entity.

In your second model, the tertiary relationship represented in the USER_HASHTAGS table seems to assume an optional many-to-many relationship between Users and Questions. If indeed your domain requires that many users can author the same question, I think model #2 would suite your needs. More likely, your requirement might explicitly restrict the ability for more than one user to author a single specific question. If so, such constraints should be accommodated in the model. Plus if a user decides to tag a question with 5 different tags, that one-to-many relationship between users and questions would be asserted 5 times in your user_hashtags table for each tag. A simple query to display the questions authored by a user would involve using DISTINCT which should immediately raise alarm bells about the design.

Assuming a one-to-many relationship between users and questions, I'd remove the USER_ID from your "USER_HASHTAGS" table and instead put the USER_ID into the QUESTIONS table as a foreign key. Then rename your USER_HASHTAGS table to QUESTION_HASHTAGS. That makes it both simple and performant because now you can simply query a single table to get the questions authored by a specific USER_ID without joining and adding who-knows-how-many duplicates the database would need to filter with DISTINCT. Also now supported is the possibility where a user chooses not to include a hashtag for their question (no blank foreign key).

NOTE:

There are many factors that influence the physical design of a database - not only the "select" access patterns, but potentially even the relative frequency of each. The ratio between database writes to reads, what can be updated, and how often in relation to other updates, etc. can also influence how you structure your tables in the end. So there is no "definitive" answer, just an answer based on a few assumptions and the limited information provided in your question.

Answers 2

Hashtags are already a kind of ID, so no need for a dedicated table for them. All you need is questions table:

create table questions (     id bigint not null constraint questions_pkey primary key,     user_id bigint constraint fk_questions_users references users,     question text not null; ) 

and questions_hashtags relation table with index by hashtag field:

create table questions_hashtags (     question_id bigint not null fk_questions_hashtags_questions references questions,     hashtag text not null,     constraint uk_questions_hashtags unique (question_id, hashtag) );  create index index_questions_hashtags_hashtag on questions_hashtags(hashtag); 

(here is a PostgreSQL dialect.)

These tables simple map to the single(!) entity (not considering User entity):

@Entity @Table(name = "questions") public class Question {     @Id     @GeneratedValue     private Long id;      @Column(nullable = false)     private String question;      @ManyToOne(optional = false)     private User user;      @CollectionTable(name = "questions_hashtags", joinColumns = @JoinColumn(name = "question_id"))     @Column(name = "hashtag")     @ElementCollection(fetch = FetchType.EAGER)     @BatchSize(size = 20)     private Set<String> hashtags = new HashSet<>();      public Question(User user, String question) {         this.user = user;         this.question = question;     }      private Set<String> extractHashtags() {       // extract hashtags from question to Set...     }      @PrePersist     @PreUpdate     private void populateHashtags() {         hashtags.clear();         hashtags.addAll(extractHashtags());     }      // other stuff } 

It's a very convenient model. To create and save question with hashtags you simply do something like this:

questionRepo.save(new Question(user, question)); 

To get all hashtags you can use this query method of your questionRepo:

@Query("select distinct h as hashtag from Question q join q.hashtags h") List<String> getAllHashtags(); 

To find all questions related to particular hashtag you can use the following query method:

@Query("select q from Question q join q.hashtags h where h = ?1") List<Question> getQuestionsByHashtag(String hashtag); 

To find questions by several hashtags you can use this method:

@Query("select q from Question q join q.hashtags h where h in (?1)") List<Question> getQuestionsByHashtag(Set<String> hashtags); 

And to find users related to the given hashtags you can use this method:

@Query("select distinct u from Question q join q.user u join q.hashtags h where h in (?1)") List<User> getUsersByHashtag(Set<String> hashtags); 

See my REST service example of hashtag usage sb-hashtag-usage-example:

1) POST /users - create new user

{     "name": "user1" } 

2) POST /questions - create new question

{     "question": "How implement best JPA #entity #model for Hashtags?",     "user": "/user/1" } 

3) GET /hashtags - get all hashtags

4) GET/questions/search/by_hashtag?hashtag=%23model - get questions by one hashtag

5) GET /questions/search/by_hashtags?hashtags=%23entity,%23model - get questions by several hashtags

6) GET /users/search/by_hashtags?hashtags=%23entity - get users by several hashtags

(Other methods like PATCH, DELETE also available.)

Read More

Monday, July 16, 2018

Does `serverTimezone` param change @@session.time_zone in MySQL?

Leave a Comment

If I'm making a connection to MySQL with serverTimezone=UTC in my connection URL, will that change the @@session.time_zone variable for my connection to MySQL? Or is the only way to alter @@session.time_zone through issuing a SET time_zone... statement? I was lead to believe that the combination of serverTimezone=UTC and useLegacyDateTimeCode=false would set the @@session.time_zone to UTC (or whatever timezone I passed in as an argument to serverTimezone) but testing this behaviour with MySQL Connector/J seems to indicate it does not.

1 Answers

Answers 1

If you want your MySQL to be configured UTC :

SET @@global.time_zone = '+00:00'; 

So every automatic update of datetime and everytime you connect to the database, @@session.time_zone will be set to @@global.time_zone.

Reboot and reconnection of the DB could be needed.

If you're just interested by the modification of the timezone of your session :

SET @@session.time_zone = '+00:00'; 

You need to do this after every connection.

Read More

Sunday, July 15, 2018

How to return different result in the same query?

Leave a Comment

I'm trying to return different result in one query, in particular the query return the ranking of a particular competition using round.id field, now sometimes this table can have the field group.id valorized, if so I need to return only the ranking which have as group.id the minimum value available, so I create this design:

SELECT l.*, t.name as team_name, r.name AS rank_name, r.color AS rank_color FROM league_ranking l LEFT JOIN team t ON l.team_id = t.id LEFT JOIN competition_ranks r ON l.rank = r.id INNER JOIN competition_groups g  WHERE l.round_id = :round_id AND l.group_id = (   SELECT MIN(l2.group_id)   FROM league_ranking l2   WHERE l2.round_id = :round_id ) 

this working if the ranking records have the group.id available, but if this field is NULL nothing will be returned, a little example of league_ranking table data:

| round_id | group_id | team_id      5         3         1045      5         3         1046      6         NULL      1047      6         NULL      1048 

if I search as round.id 5, will be returned the first two records, but if instead I search for round.id 6, nothing will be returned. How can I structure my query to return the result also if there is no group.id associated?

1 Answers

Answers 1

null isn't a value, it's the lackthereof. null = null returns null, not true, so for groups without an id, this query won't work.

You can use the <=> instead of =, though, to evaluate two nulls as being equal:

SELECT l.*, t.name as team_name, r.name AS rank_name, r.color AS rank_color FROM league_ranking l LEFT JOIN team t ON l.team_id = t.id LEFT JOIN competition_ranks r ON l.rank = r.id INNER JOIN competition_groups g  WHERE l.round_id = :round_id AND l.group_id <=> ( -- <=> used here instead of =   SELECT MIN(l2.group_id)   FROM league_ranking l2   WHERE l2.round_id = :round_id ) 
Read More

Saturday, July 7, 2018

Solr multiple sort results, but first premium (true) posts

Leave a Comment

I have start learning Solr, and trying to understand and implement same query like one i have done in mysql, to return results in same order and logic.

What i need:

  • return allways first posts marked as premium (bool, true), then other
  • sort / order all by date created new > old..

default mysql example query / without search params:

SELECT    *  FROM    postings Postings    // LEFT JOIN query .. WHERE    (     // where query..   )  ORDER BY    Postings.premium DESC, // <--- bool (1),    FIELD(Postings.source, "local") DESC,    Postings.cpc DESC  

and example with search parameter:

SELECT    MATCH (Postings.title) AGAINST ('developer' IN BOOLEAN MODE) AS `Postings__relavance_title`,    MATCH (Postings.description) AGAINST ('developer' IN BOOLEAN MODE) AS `Postings__relavance_description`,    // other Fields  FROM    postings Postings    // LEFT JOIN queries ... WHERE    (     MATCH (       Postings.title, Postings.description     ) AGAINST ('developer' IN BOOLEAN MODE)    )  ORDER BY    (Postings__relavance_title * 2)+ Postings__relavance_description DESC,    Postings.premium DESC, // <--- bool (1)   FIELD(Postings.source, "local") DESC,    Postings.cpc DESC 

How to sort / order solr data in same way?

2 Answers

Answers 1

Clearly you understand the SQL tricks to achieve your goal.

I don't know Solr, but that sounds rather complex for a 3rd party software to provide for. If there is a way to hand-code SQL (and have Solr simply pass it through), I suggest you do it that way.

Answers 2

You can give Solr a set of sort criteria:

&sort=premium desc, date_created desc 

... this will give you all the premium posts first, then all the non-premium posts, while being ordered by date_created inside each group.

This assumes that you have indexed your boolean field in Solr as a boolean / int field. Also, sorting by fields are more efficient if you've enabled docValues for those fields, but that will be on by default for the fields that support them in the most recent versions of Solr.

Read More

Sunday, July 1, 2018

how to add mysql dependencies in react

Leave a Comment

i am trying to resolve this error from a long time and i had asked this lots of time but not able to remove this i am trying to add mysql dependencies in reactjs i am running

npm install mysql 

but its giving me

npm ERR! Unexpected end of JSON input while parsing near  '....tgz"},"engines":{"no'  npm ERR! A complete log of this run can be found in: npm ERR!     C:\Users\HP\AppData\Roaming\npm-cache\_logs\2018-06-  22T01_58_05_155Z-debug.log 

i uninstalled my npm and install it again and try to run npm install --save react-router-dom now its saying

npm install --save react-router-dom  npm WARN deprecated istanbul-lib-hook@1.2.1: 1.2.0 should have been a major version bump npm ERR! Unexpected end of JSON input while parsing near '...9a3f270fa24dbccdd5014'  npm ERR! A complete log of this run can be found in: npm ERR!     C:\Users\HP\AppData\Roaming\npm-cache\_logs\2018-06-26T18_57_32_102Z-debug.log 

2 Answers

Answers 1

Your package.json file has a syntax error. For finding the error use JSON validator, for example, jsonlint.com. Also, every modern IDE has auto-validating features.

Answers 2

This solved it for me:

1. Clean your npm cache

run this command in your project root folder:

npm cache clean --force

2. Delete package.lock.json

3. Delete node_modules folder

run again

npm install

Read More

Wednesday, June 20, 2018

Is there another way to “setConnection” on an Eloquent Model?

Leave a Comment

I am currently handling a "multi db on the fly swap connections" sort of project.

So what I end up doing is the following:

$connectionName = uniqid(); \Config::set('database.connections.' . $connectionName, [/** db options **/]); \Artisan::call('migrate', ['--database' => $connectionName]); 

or

$connectionName = uniqid();            \Config::set('database.connections.' . $connectionName,[/** db options **/]);  $user = new User(); $user->setConnection($connectionName); $user->first_name = 'Daisy'; $user->last_name = 'Demo'; $user->is_not_being_ignored_by_santa_this_year = 0; $user->email = //and so so on $user->save(); 

For the Artisan call I sort of understand why Laravel needs to refer to a connection in a string, saved in a config array.

However on the Eloquent Model itself I find it somehow cumbersome to have to write my DB connection into a config array. So it can be picked up by the "Singleton approach" \Config::get().. in the Model.

Is there something more elegant, where I can inject a configuration directly without having to write it into some super global ?

Or am I missing something ?

4 Answers

Answers 1

You would probably be better off creating a configuration array for each connection then you could switch between connections pretty easily by specifying which connection to use.

If you need to use multiple connections on the same model you can use the on method:

so it would be something like User::on('dbconnection2')->find(1)

If you just want to use different connections for different models, you can set the protected $connection property on the model:

class User extends Model {     protected $connection = 'dbconnection2'; } 

Hope that helps.

Answers 2

You could create a factory for your models and pass it the connection on bootstrapping your app:

<?php  class ModelFactory {     private $db;      public function __construct($dbConnection)     {         $this->db = $dbConnection;     }      public function createNewModel($class)     {         $object = new $class();         $object->setConnection($this->db);         return $object;     } } 

Then in your code:

$user = $factory->createModel(User::class); 

Something like this! Good luck! :-)

Answers 3

Its all depends on how you handling your multiple connections.I have worked on similar requirement project.

  • we have master slave/tenant database connection. with configuration https://gist.github.com/safoorsafdar/c6c623f9ec7b440f563d76995faf7aec#file-database-php
  • tenant database/migration/seeds create on the fly with create new account in the system
  • can soft delete database from the root control.
  • on the user login, we check if its master, connect to master connection otherwise get tenant connection, store information in the session for web access. check Tenant Setup after login.
  • Database connection related operation central class. View DatabaseConnection.
  • center tenant session handler class to help with resolve tenant id from the session. View TenantContextSession
  • we have separate models with abstract class for tenant and master to get set the model connection. Check
  • You might also need to handle migration in your system, have look into this https://gist.github.com/safoorsafdar/cc9252a2f14301c3da942ca7bec7d66e

Tenant Model Abstract Class

<?php  namespace App\Models\Abstracts;  use App\Models\Abstracts\AbstractBaseModel; use App\Models\Picklist\PicklistValue;  class TenantAbstractBaseModel extends AbstractBaseModel {     function __construct(array $attributes = array())     {         parent::__construct($attributes);         if ( ! is_null(app('tenant.context')->getConnectionName())) {             $this->setConnection(app('tenant.context')->getConnectionName());         }          //todo; should be dynamic         if (is_null(app('tenant.context')->getConnectionName())             && app()->runningInConsole()         ) {             //todo; need to resolve database connection through terminal and application.             //dd(config('tenant.tenant_connection'));             //$this->setConnection(config('tenant.tenant_connection'));         }      } } 

Tenant Setup after login

$connection = config('tenant.tenant_connection');                 //config()->set('database.default', config('tenant.tenant_connection'));             app('tenant.context')->setConnectionName($connection);             app('tenant.context')->setTenantId($company_id);               //$database = config('database.connections.' . $connection . '.database') . $company_id;              $company_system_name                     = $this->auth->user()->company->system_name;              config()->set('database.connections.'.$connection.'.database',                     $company_system_name);              //config()->set('database.connections.' . $connection . '.database', $database);            config()->set('database.default', $connection); 

DatabaseConnection

<?php  namespace App\Tenancy\Tenant;  use Config; use DB; use App\Tenancy\Exceptions\TenantDatabaseException; use App\Tenancy\Models\Tenant;  /**  * Class DatabaseConnection  *  * Helps with tenant database connections  */ class DatabaseConnection {     /**      * See the multi-tenant configuration file. Configuration set      * to use separate databases.      */     const TENANT_MODE_SEPARATE_DATABASE = 'database';      /**      * See the multi-tenant configuration file. Configuration set      * to use prefixed table in same database.      */     const TENANT_MODE_TABLE_PREFIX = 'prefix';     /**      * Current active global tenant connection.      *      * @var string      */     protected static $current;     /**      * @var string      */     public $name;     /**      * @var Tenant      */     protected $tenant;     /**      * @var \Illuminate\Database\Connection      */     protected $connection;      public function __construct(Tenant $tenant)     {         $this->tenant = $tenant;          $this->name = "tenant.{$this->tenant->hash_id}";          $this->setup();     }      /**      * Sets the tenant database connection.      */     public function setup()     {         Config::set("database.connections.{$this->name}", $this->config());     }      /**      * Generic configuration for tenant.      *      * @return array      */     protected function config()     {         $clone             = Config::get(sprintf('database.connections.%s',             static::tenantConnectionName()));         $clone['database'] = $this->tenant->system_name;          return $clone;     }      /**      * Central getter for system connection name.      *      * @return string      */     public static function systemConnectionName()     {         return Config::get('tenant.master_connection', 'mysql');     }      /**      * Checks whether current connection is set as global tenant connection.      *      * @return bool      */     public function isCurrent()     {         return $this->name === static::getCurrent();     }      /**      * Loads the currently set global tenant connection name.      *      * @return string      */     public static function getCurrent()     {         return static::$current;     }      /**      * Sets current global tenant connection.      */     public function setCurrent()     {         static::$current = $this->name;         Config::set(sprintf('database.connections.%s',             static::tenantConnectionName()), $this->config());          DB::purge(static::tenantConnectionName());     }      /**      * Central getter for tenant connection name.      *      * @return string      */     public static function tenantConnectionName()     {         return Config::get('tenant.tenant_connection', 'tenant_mysql');     }      /**      * Loads connection for this database.      *      * @return \Illuminate\Database\Connection      */     public function get()     {         if (is_null($this->connection)) {             $this->setup();             $this->connection = DB::connection($this->name);         }          return $this->connection;     }      /**      * @return bool      */     public function create()     {         $clone = $this->config();          return DB::connection(static::systemConnectionName())             ->transaction(function () use ($clone) {                 if ( ! DB::connection(static::systemConnectionName())                     ->statement("create database if not exists `{$clone['database']}`")                 ) {                     throw new TenantDatabaseException("Could not create database {$clone['database']}");                 }                 if ( ! DB::connection(static::systemConnectionName())                     ->statement("grant all on `{$clone['database']}`.* to `{$clone['username']}`@'{$clone['host']}' identified by '{$clone['password']}'")                 ) {                     throw new TenantDatabaseException("Could not create or grant privileges to user {$clone['username']} for {$clone['database']}");                 }                  return true;             });     }      /**      * @throws \Exception      *      * @return bool      */     public function delete()     {         $clone = $this->config();          return DB::connection(static::systemConnectionName())             ->transaction(function () use ($clone) {                 if ( ! DB::connection(static::systemConnectionName())                     ->statement("revoke all on `{$clone['database']}`.* from `{$clone['username']}`@'{$clone['host']}'")                 ) {                     throw new TenantDatabaseException("Could not revoke privileges to user {$clone['username']} for {$clone['database']}");                 }                 if ( ! DB::connection(static::systemConnectionName())                     ->statement("drop database `{$clone['database']}`")                 ) {                     throw new TenantDatabaseException("Could not drop database {$clone['database']}");                 }                  return true;             });     } } 

*TenantContextSession *

<?php  namespace App\Repositories\Tenant;  use App\Repositories\Tenant\TenantContextRepositoryContract;  /**  * Description of TenantContextSession  *  * @author safoor  */ class TenantContextSession implements TenantContextRepositoryContract { //    public function __construct() { //        $this->clearTenantSession(); //    }      /**      * Sets the connection name for the actual context      * this tenant      * @param $name      * @return mixed      */     public function setConnectionName($name)     {         if (session()->has('tenant_connection')) {             session()->set('tenant_connection', '');         }          session()->put('tenant_connection', $name);     }      /**      * Get the name of the current connection in context      * @return mixed      */     public function getConnectionName()     {         return session()->get('tenant_connection');     }      /**      * Sets the id value filter data in the current context      * @param $id      * @return mixed      */     public function setTenantId($id)     {         if (session()->has('tenant_id')) {             session()->set('tenant_id', '');         }         session()->put('tenant_id', $id);     }      /**      *      * @return mixed      */     public function getTenantId()     {         return session()->get('tenant_id');     }      public function clearTenantSession()     {         session()->flush();         session()->set('tenant_id', '');         session()->set('tenant_connection', '');     } } 

I hope this will help to work with your scenario, I have tried to mention all of aspect we had to covered, but if still there is something confusing and need explanation from my side please let me know.

Answers 4

I build a multitenant laravel app and was surprised that there is no out-of-the-box way of doing that.

I have one app available via different subdomains and the subdomain should be the key to different configs, like the database connection.

You can easily adapt that to whatever criteria you need instead of the subdomain.

Via dynamically Config::set()

So my first attempt was to always use the "default" connection and to create a middleware that dynamically calls Config::set("database.connection.default.host", "1.3.5.7"); and so on for all the other settings.

But there are some downsides. For example it was pretty slow because I read all the values from the database and later on from redis. But the much bigger problem was to set the connection to the redis cache for example, because the redis connection is already established before the middleware it called to override the config setting.

Via own config files

So my second and current approach is to make it all via config files. So I created the following file structure:

  • config/_myapp.php
  • config/subdomain1/_myapp.php

Note: The underscore is important because the files are read in alphabetic order and our new file has to be read at first to use it in other config files.

The goal is to use config('_myapp.DB_HOST') to retrieve the DB_HOST value from config/[subdomain]/_myapp.php and use that as value in config/database.php. So config/_myapp.php only returns the content of _myapp.php for the specific subdomain.

in config/_myapp.php:

// get the current subdomain from $_SERVER['HTTP_HOST'] $subdomain = \App\Helper::getSubDomain();  define('SUBDOMAIN', $subdomain);  if(!empty($subdomain) && file_exists($file = __DIR__."/$subdomain/".basename(__FILE__)))     return require($file);  return [  ]; 

and in config/_myapp.php:

return [     ...     'DB_HOST' => '1.3.5.7',     ... ]; 

Use this for example in config/database.php or whereever you need domain specific config:

...    'host' => config('_myapp.DB_HOST'), ... 

Please ask if something doesn't work, took me quite some time to figure that stuff out.

Read More

Monday, June 18, 2018

How to show time difference over 24 hours between timestamps

Leave a Comment

I have a query that returns speed to response. It works correctly expect for instances when the timediff calculation results is over 24 hours. I get a error of "java.sql.SQLException: Illegal hour value '31' for java.sal.Time type in value"

The number of '31' varies with the variance of hours between the timestamps.

I'm not sure where to precede from here. I tried timestampdiff() but get an error while trying to run the query.

Any comments or suggestions would be much appreciated.

SELECT a.* FROM (SELECT databunker.purchases.id                                           AS 'pur_id',  databunker.purchases.business                                    AS 'pur_business',  databunker.purchases.time                                        AS 'pur_time',  databunker.customers.id                                          AS 'customer_id',  databunker.customers.phone_number                                AS 'customer_phone_#',  databunker.customers.is_primary                                  AS 'customer_is_primary',  map.object_salesforce_id,  databunker.five9_calls.campaign_name,  databunker.five9_calls.start_timestamp AS 'start_of_call',  TIMEDIFF(databunker.five9_calls.start_timestamp, databunker.purchases.time) AS 'speed_to_response'  FROM databunker.purchases  LEFT OUTER JOIN databunker.customers ON (databunker.purchases.customer_id = databunker.customers.id)  LEFT OUTER JOIN (SELECT                     databunker.mappings.object_salesforce_id,                     databunker.mappings.object_id AS 'map_customer_id'                   FROM databunker.mappings                   WHERE databunker.mappings.object_class = 'customer') AS map    ON (databunker.purchases.customer_id = map.map_customer_id)  LEFT OUTER JOIN databunker.five9_calls ON (map.object_salesforce_id =  databunker.five9_calls.salesforce_id) WHERE databunker.purchases.business = 'uma'      AND databunker.purchases.outcome_type = 'accepted'      AND databunker.purchases.time >= curdate() - 1       AND databunker.five9_calls.start_timestamp >= databunker.purchases.time  GROUP BY  databunker.purchases.id,  databunker.purchases.business,  databunker.purchases.time,  databunker.customers.id,  databunker.customers.phone_number,  map.object_salesforce_id,  databunker.five9_calls.campaign_name,  databunker.five9_calls.start_timestamp,  TIMEDIFF(databunker.five9_calls.start_timestamp, databunker.purchases.time)   ORDER BY databunker.purchases.id, databunker.purchases.time,   databunker.five9_calls.start_timestamp ASC) a  INNER JOIN  ( SELECT   databunker.purchases.id AS 'pur_id_2',   MIN(databunker.five9_calls.start_timestamp) AS 'call_time'   FROM databunker.purchases   LEFT OUTER JOIN databunker.customers ON (databunker.purchases.customer_id = databunker.customers.id)   LEFT OUTER JOIN (SELECT                      databunker.mappings.object_salesforce_id,                      databunker.mappings.object_id AS 'map_customer_id'                    FROM databunker.mappings                    WHERE databunker.mappings.object_class = 'customer') AS map     ON (databunker.purchases.customer_id = map.map_customer_id)   LEFT OUTER JOIN databunker.five9_calls ON (map.object_salesforce_id = databunker.five9_calls.salesforce_id) WHERE databunker.purchases.business = 'uma'       AND databunker.purchases.outcome_type = 'accepted'       AND databunker.purchases.time >= curdate() - 1        AND databunker.five9_calls.start_timestamp >= databunker.purchases.time  GROUP BY   databunker.purchases.id ) b  ON a.pur_id = b.pur_id_2 AND a.start_of_call = b.call_time 

enter image description here

1 Answers

Answers 1

There is "time of day" and there is "time span".

MySQL's TIMEDIFF() is returning a "time span" of 31 hours, etc.

Your Java code is expecting a "time of day" which, of course, should not be more than 23:59:59 (ignoring leap seconds).

One workaround is to say

TO_SECONDS(databunker.five9_calls.start_timestamp) - TO_SECONDS(databunker.purchases.time) 

but that won't return (for example) "31:58:47"; instead it will give "115127".

Another workaround is to avoid java.sal.Time and find a library that handles "time spans".

Read More

Friday, June 15, 2018

MySQL conditional referencing of foreign key

Leave a Comment

I'm currently working on a schema with nullable foreign key. Basically, this is what I want to achieve:

Given:

table 1:

game:   id   observer_id   starts_on   ends_on   type 

table 2:

observer:   id   game_id DEFAULT NULL   starts_on   ends_on   type   FOREIGN KEY (`game_id`) REFERENCES `game`(`id`) ON DELETE SET NULL 

Now, what I want to do - I want to duplicate as the initial values and update on cascade starts_on, ends_on and type fields in observer table if I have a reference to a game, however if game_id is null I want to have an independent values for above mentioned fields. Is something like this possible with IF in mysql or should I implement the logic in my model files?

2 Answers

Answers 1

Consider to solve your issue while data retrieving (SELECT) instead of data manipulation (INSERT/UPDATE/DELETE).

select     o.id,     o.game_id,     coalesce(g.starts_on, o.starts_on) as starts_on,     coalesce(g.ends_on,   o.ends_on)   as ends_on,     coalesce(g.type,      o.type)      as type from observer o left join game g on g.id = o.game_id 

In this query if o.game_id is NULL the LEFT JOIN will find no matches in the game table and all its columns will also be NULL. Then COALESCE() will take care of choosing the value from the game table if present or from observer otherwise.

You can use that query in a VIEW (if you like), but i can't tell if it will perform well in any use case.

This way you can store your "independent" values without worrying if the game id is set or not, since they will only be used, if the game_id is not NULL.

Note that your problem might be solved in a more "clean" way changing the schema. With the columns game.observer_id and observer.game_id it looks like a cyclic relation, which can be considered as "design smell". But without knowledge of your data logic I can't suggest a better way.

Answers 2

FOREIGN KEYs do a limited number of things. Once you go beyond them, you should build your own transaction in your app code (or Stored Procedure or ...) to do the more complex things.

I feel that this is the safer route, since you know exactly what you need, and won't have to try to shoehorn FKs into doing it.

Read More

Saturday, June 9, 2018

Is there a way to have table name automatically added to Eloquent query methods?

Leave a Comment

I'm developing an app on Laravel 5.5 and I'm facing an issue with a specific query scope. I have the following table structure (some fields omitted):

orders --------- id parent_id status 

The parent_id column references the id from the same table. I have this query scope to filter records that don't have any children:

public function scopeNoChildren(Builder $query): Builder {     return $query->select('orders.*')         ->leftJoin('orders AS children', function ($join) {             $join->on('orders.id', '=', 'children.parent_id')                 ->where('children.status', self::STATUS_COMPLETED);         })         ->where('children.id', null); } 

This scope works fine when used alone. However, if I try to combine it with any another condition, it throws an SQL exception:

Order::where('status', Order::STATUS_COMPLETED)     ->noChildren()     ->get(); 

Leads to this:

SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'status' in where clause is ambiguous

I found two ways to avoid that error:

Solution #1: Prefix all other conditions with the table name

Doing something like this works:

Order::where('orders.status', Order::STATUS_COMPLETED)     ->noChildren()     ->get(); 

But I don't think this is a good approach since it's not clear the table name is required in case other dev or even myself try to use that scope again in the future. They'll probably end up figuring that out, but it doesn't seem a good practice.

Solution #2: Use a subquery

I can keep the ambiguous columns apart in a subquery. Still, in this case and as the table grows, the performance will degrade.

This is the strategy I'm using, though. Because it doesn't require any change to other scopes and conditions. At least not in the way I'm applying it right now.

public function scopeNoChildren(Builder $query): Builder {     $subQueryChildren = self::select('id', 'parent_id')         ->completed();     $sqlChildren = DB::raw(sprintf(         '(%s) AS children',         $subQueryChildren->toSql()     ));      return $query->select('orders.*')         ->leftJoin($sqlChildren, function ($join) use ($subQueryChildren) {             $join->on('orders.id', '=', 'children.parent_id')                 ->addBinding($subQueryChildren->getBindings());          })->where('children.id', null); } 

The perfect solution

I think that having the ability to use queries without prefixing with table name without relying on subqueries would be the perfect solution.

That's why I'm asking: Is there a way to have table name automatically added to Eloquent query methods?

3 Answers

Answers 1

I would use a relationship:

public function children() {     return $this->hasMany(self::class, 'parent_id')         ->where('status', self::STATUS_COMPLETED); }  Order::where('status', Order::STATUS_COMPLETED)     ->whereDoesntHave('children')     ->get(); 

This executes the following query:

select * from `orders` where `status` = ?   and not exists     (select *      from `orders` as `laravel_reserved_0`      where `orders`.`id` = `laravel_reserved_0`.`parent_id`        and `status` = ?) 

It uses a subquery, but it's short, simple and doesn't cause any ambiguity problems.

I don't think that performance will be a relevant issue unless you have millions of rows (I assume you don't). If the subquery performance will be a problem in the future, you can still go back to a JOIN solution. Until then, I would focus on code readability and flexibility.

A way to reuse the relationship (as pointed out by the OP):

public function children() {     return $this->hasMany(self::class, 'parent_id'); }  Order::where('status', Order::STATUS_COMPLETED)     ->whereDoesntHave('children', function ($query) {         $query->where('status', self::STATUS_COMPLETED);     })->get(); 

Or a way with two relationships:

public function completedChildren() {     return $this->children()         ->where('status', self::STATUS_COMPLETED); }  Order::where('status', Order::STATUS_COMPLETED)     ->whereDoesntHave('completedChildren')     ->get(); 

Answers 2

In MySQL there are two good ways to find the leaf nodes (rows) in an adjacency list. One is the LEFT-JOIN-WHERE-NULL method (antijoin), which is what you did. The other is a NOT EXISTS subquery. Both methods should have a comparable performance (in theory they do exactly the same). However the subquery solution will not introduce new columns to the result.

return $query->select('orders.*')     ->whereRaw("not exists (         select *         from orders as children         where children.parent_id = orders.id           and children.status = ?     )", [self::STATUS_COMPLETED]); 

Answers 3

You must create a SomeDatabaseBuilder extending the original Illuminate\Database\Query\Builder, and a SomeEloquentBuilder extending the Illuminate\Database\Eloquent\Builder and, finally, a BaseModel extending Illuminate\Database\Eloquent\Model and overwrite these methods:

/**  * @return SomeDatabaseBuilder  */ protected function newBaseQueryBuilder() {     $connection = $this->getConnection();      return new SomeDatabaseBuilder(         $connection, $connection->getQueryGrammar(), $connection->getPostProcessor()     ); }  /**  * @param \Illuminate\Database\Query\Builder $query  * @return SameEloquentBulder  */ public function newEloquentBuilder($query) {     return new SameEloquentBulder($query); } 

Then, on SomeDatabaseBuilder and SameEloquentBulder, change the methods to qualify columns by default (or make it optional).

Read More

Thursday, May 31, 2018

Lookup against MYSQL TEXT type column

Leave a Comment

My table/model has TEXT type column, and when filtering for the records on the model itself, the AR where produces the correct SQL and returns correct results, here is what I mean :

MyNamespace::MyValue.where(value: 'Good Quality') 

Produces this SQL :

SELECT `my_namespace_my_values`.*  FROM `my_namespace_my_values`  WHERE `my_namespace_my_values`.`value` = '\\\"Good Quality\\\"' 

Take another example where I m joining MyNamespace::MyValue and filtering on the same value column but from the other model (has relation on the model to my_values). See this (query #2) :

OtherModel.joins(:my_values).where(my_values: { value: 'Good Quality' }) 

This does not produce correct query, this filters on the value column as if it was a String column and not Text, therefore producing incorrect results like so (only pasting relevant where) :

WHERE my_namespace_my_values`.`value` = 'Good Quality' 

Now I can get past this by doing LIKE inside my AR where, which will produce the correct result but slightly different query. This is what I mean :

OtherModel.joins(:my_values).where('my_values.value LIKE ?, '%Good Quality%') 

Finally arriving to my questions. What is this and how it's being generated for where on the model (for text column type)?

WHERE `my_namespace_my_values`.`value` = '\\\"Good Quality\\\"' 

Maybe most important question what is the difference in terms of performance using :

WHERE `my_namespace_my_values`.`value` = '\\\"Good Quality\\\"' 

and this :

(my_namespace_my_values.value LIKE '%Good Quality%') 

and more importantly how do I get my query with joins (query #2) produce where like this :

WHERE `my_namespace_my_values`.`value` = '\\\"Good Quality\\\"' 

4 Answers

Answers 1

(Partial answer -- approaching from the MySQL side.)

What will/won't match

Case 1: (I don't know where the extra backslashes and quotes come from.)

WHERE `my_namespace_my_values`.`value` = '\\\"Good Quality\\\"'  \"Good Quality\"               -- matches Good Quality                   -- does not match The product has Good Quality.  -- does not match 

Case 2: (Find Good Quality anywhere in value.)

WHERE my_namespace_my_values.value LIKE '%Good Quality%'  \"Good Quality\"               -- matches Good Quality                   -- matches The product has Good Quality.  -- matches 

Case 3:

WHERE `my_namespace_my_values`.`value` = 'Good Quality'  \"Good Quality\"               -- does not match Good Quality                   -- matches The product has Good Quality.  -- does not match 

Performance:

  • If value is declared TEXT, all cases are slow.
  • If value is not indexed, all are slow.
  • If value is VARCHAR(255) (or smaller) and indexed, Cases 1 and 3 are faster. It can quickly find the one row, versus checking all rows.

Phrased differently:

  • LIKE with a leading wildcard (%) is slow.
  • Indexing the column is important for performance, but TEXT cannot be indexed.

Answers 2

What is this and how it's being generated for where on the model (for text column type)?

Thats generated behind Active Records (Arel) lexical engine. See my answer below on your second question as to why.

What is the difference in terms of performance using...

The "=" matches by whole string/chunk comparison While LIKE matches by character(s) ( by character(s)).

In my projects i got tables with millions of rows, from my experience its really faster to the use that comparator "=" or regexp than using a LIKE in a query.

How do I get my query with joins (query #2) produce where like this...

Can you try this,

OtherModel.joins(:my_values).where(OtherModel[:value].eq('\\\"Good Quality\\\"')) 

Answers 3

I think it might be helpful.

to search for \n, specify it as \n. To search for \, specify it as \\ this is because the backslashes are stripped once by the parser and again when the pattern match is made, leaving a single backslash to be matched against.

link

LIKE and = are different operators.

= is a comparison operator that operates on numbers and strings. When comparing strings, the comparison operator compares whole strings.

LIKE is a string operator that compares character by character.

mysql> SELECT 'ä' LIKE 'ae' COLLATE latin1_german2_ci; +-----------------------------------------+ | 'ä' LIKE 'ae' COLLATE latin1_german2_ci | +-----------------------------------------+ |                                       0 | +-----------------------------------------+ mysql> SELECT 'ä' = 'ae' COLLATE latin1_german2_ci; +--------------------------------------+ | 'ä' = 'ae' COLLATE latin1_german2_ci | +--------------------------------------+ |                                    1 | +--------------------------------------+ 

Answers 4

The '=' op is looking for an exact match while the LIKE op is working more like pattern matching with '%' being similar like '*' in regular expressions.

So if you have entries with

  1. Good Quality
  2. More Good Quality

only LIKE will get both results.

Regarding the escape string I am not sure where this is generated, but looks like some standardized escaping to get this valid for SQL.

Read More