When using clojure's korma sqlite3 helpers, what's the default path for the sqlite3 database? - sqlite

When using korma.db, defdb can take a sqlite3 helper to establish a connexion to a sqlite3 database. However, I've tried placing the database on the root of the project directory, alongside project.clj, and on the resources directory, but when I try to use the db I get:
Failure to execute query with SQL:
SELECT "examples".* FROM "examples" :: []
SQLException:
Message: [SQLITE_ERROR] SQL error or missing database (no such table: examples)
Needless to say my sqlite database contains an examples table. When trying to do this, I get a sqlite.db file of zero bytes placed on the root project dir.
I'm doing this from lein repl within the project, by the way.
Edit: This is what I do when it fails:
(use 'korma.db)
(defdb db (sqlite3 {:db "filename.db"}))
(use 'korma.core)
(defentity examples)
(select examples)

Just in case anybody is wondering or runs into this...
Using version [korma "0.4.2"]
and [org.xerial/sqlite-jdbc "3.7.15-M1"]
in my project.clj:
My project structure looks like:
root/project.clj
root/db/dev.sqlite3
root/src/...
and this is how I use korma to access the db:
(use 'korma.db)
(defdb mydb {:classname "org.sqlite.JDBC"
:subprotocol "sqlite"
:subname "db/dev.sqlite3"})
Basically, using subname, I'm able to search in the root of the lein project. I added db/ in the subname per my dir structure above.

Related

How to migrate data to new server? (Sequence generator issue)

What is the right way to backup and restore a MariaDB database that has sequence generation enabled (i.e. NOT autoincrement)? (This includes migrating to a new server.)
Is it possible to instruct the sequence generator to pick up indexing table data at a specific ID value? How?
Steps I take to create my issue
I wish to transfer an application to a new server:
Backup data on source server:
mysqldump --skip-opt --no-create-db --no-create-info --hex-blob [database-name] [...list of tables...] > data-backup.sql
On target server, create new empty database (same name)
Build/run JHipster Spring application on target server: java -jar myapp.jar (Running this application recreates/configures a new instance of the database on the target server.)
Restore data:
mysql [database-name] < data-backup.sql
All the above steps produce no errors (so far).
Problem
When I follow these steps, the database is restored (apparently perfectly). I can log in to the application and access all information. BUT when I attempt to create new entities (i.e. save something to the database), I get an ID 'Duplicate entry' error in the server logs:
2022-03-24 12:54:43.775 ERROR 11277 --- [ XNIO-1 task-1] o.h.e.jdbc.batch.internal.BatchingBatch : HHH000315: Exception executing batch [java.sql.BatchUpdateException: (conn=33) Duplicate entry '1001' for key 'PRIMARY'], SQL: insert into product (name, id) values (?, ?)
2022-03-24 12:54:43.776 WARN 11277 --- [ XNIO-1 task-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1062, SQLState: 23000
2022-03-24 12:54:43.776 ERROR 11277 --- [ XNIO-1 task-1] o.h.engine.jdbc.spi.SqlExceptionHelper : (conn=33) Duplicate entry '1001' for key 'PRIMARY'
2022-03-24 12:54:43.779 ERROR 11277 --- [ XNIO-1 task-1] o.z.problem.spring.common.AdviceTraits : Internal Server Error
org.springframework.dao.DataIntegrityViolationException: could not execute batch; SQL [insert into product (name, id) values (?, ?)]; constraint [PRIMARY]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute batch
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:276)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:233)
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:566)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:743)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:711)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:654)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:407)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:753)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:698)
at com.mycompany.app.web.rest.ProductResource$$EnhancerBySpringCGLIB$$84c14d6d.createProduct(<generated>)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
...
Clearly my backup/restore process is not accounting properly for the sequence generator, which generates ID values that conflict with the existing data.
What I am doing wrong? What is the right process of backing up/restoring such a database?
Environment: JHipster 7.7.0 (Angular, monolithic), MariaDB 10.4, OpenJDK 16.0.2_7, OS Windows 10 Pro and openSUSE 15.2, Firefox 98.0.2 and Chrome 99.0.4844.84.
PS: I previously reported this issue here, aimed at the JHipster community, but got limited response. I think I need a MySQL/MariaDB expert opinion on this.
(Apologies in advance: I'm not a database expert. The technique I outline above has served me well for years, but previously I was dealing with AUTO_INCREMENT. This sequence generator has me baffled.)
Ok! I have solutions.
[For the sake if these notes, let's call the database: mydata. Also, in JHipster, the MariaDB sequence generator is called: sequence_generator]
Let's consider two situations:
(1) Simple migration
If you are merely migrating the application to a new server, the process is straight forward:
Step 1: On the original server backup and secure your database: mysqldump -u root -p mydata > mydata.sql
Step 2: Transfer the SQL file to the new server, along with the JHipster JAR file
Step 3: On the new server, create an empty database with the same name, and restore the data: mysql -u root -p mydata < mydata.sql
Step 4: Now launch your JHipster application, and everything should work
(2) Model modification
The assumption is that you have modified your model in some way (e.g. added properties to one or more entities). This solution is fiddly, but it works (for me).
Step 1: Backup your database, and secure it (in case something goes wrong): mysqldump -u root -p mydata > mydata.sql
Step 2: Backup and secure the original JHipster JAR that works with the original database
Step 3: Duplicate your database (schema and data) in a new table: mydata_bk
Step 4: Drop your original database, and create a new empty database
Step 5: Launch your new JHipster JAR, and give it time to create the new database schema, then stop the application
Step 6: Use a tool (DataGrip, sqlYog, etc) to compare the old (mydata_bk) and new schema (mydata), and modify the old schema to match the new schema
Step 7: Restore/copy all data from mydata_bk to mydata, EXCEPT for the tables DATABASECHANGELOG, DATABASECHANGELOGLOCK and the special sequence_generator table
Step 8: Open the mydata.sql SQL file, and at the top, after initial comments, one of the first instructions will read:
--
-- Sequence structure for `sequence_generator`
--
DROP SEQUENCE IF EXISTS `sequence_generator`;
CREATE SEQUENCE `sequence_generator` start with 2000 minvalue 1 maxvalue 9223372036854775806 increment by 50 cache 1000 nocycle ENGINE=InnoDB;
SELECT SETVAL(`sequence_generator`, 201050, 0);
The specific numbers may vary, but the broad details will be similar. In a MariaDB SQL console type/execute each of those SQL statements: DROP SEQUENCE ...;, CREATE SEQUENCE ...;, and SELECT SETVAL(...);
Step 9: Launch your JHipster application.
Hope this helps others that run into similar issues. Let me know if you have a better approach!

Liquibase SQL Changeset Cannot Load CSV File : FileNotFoundException

Using a SQL style approach to Liquibase changesets (which is our codestyle, we don't use XML) I am trying to load an CSV file using the following SQL changeset
SQL
-- changeset user:insert-prices-data-temp-table
LOAD DATA LOCAL INFILE 'foo/src/main/resources/liquibase/changelogs/2021/prices.csv'
INTO TABLE prices_temp
FIELDS TERMINATED BY ',' ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES
When deploying the WAR file to Wildfly the following exception
java.io.FileNotFoundException:
foo/src/resources/liquibase/changelogs/2021/prices.csv (No such file
or directory) 2021-09-22T20:52:18.581085123Z at
java.io.FileInputStream.open0(Native Method)
2021-09-22T20:52:18.581087214Z at
java.io.FileInputStream.open(FileInputStream.java:195)
2021-09-22T20:52:18.581089768Z at
java.io.FileInputStream.(FileInputStream.java:138)
2021-09-22T20:52:18.581092029Z at
java.io.FileInputStream.(FileInputStream.java:93)
2021-09-22T20:52:18.581094150Z at
com.mysql.jdbc.MysqlIO.sendFileToServer(MysqlIO.java:3772)
The Master Change log file references the 2021 directory with the SQL and CSV file existing in the same directory.
<includeAll path="liquibase/changelogs/2021/" filter="xml" errorIfMissingOrEmpty="true" />
I have tried the following other paths but they all still yield a FileNotFoundException
prices.csv
liquibase/changelogs/2021/prices.csv
WEB-INF/classes/liquibase/changelogs/2021/CCC-220-marking-time-prices.csv
(Absolute path) /home/xxxx/Work/foo-service/foo/src/main/resources/liquibase/changelogs/2021/prices.csv
Liquibase Version: 3.5.1
Wildfly Jboss Version : 21
I have checked the CSV file is present in the WAR file
Any ideas how to fix this?
The problem is that you are trying to use some mysql function LOAD DATA LOCAL INFILE which doesn't know about your classpath. It's trying to look at your filesystem and such path doesn't exists. Even if you provide something like yourapp.jar!liquibase/changelogs/2021/prices.csv it won't be able to read that file. You will need to pull prices.csv out of your application to filesystem and point mysql function to that location.
Or you can use liquibase's loadData if that helps.

Run PDO SQLite Query On In-Memory Database On Github Actions

I use PHPUnit to test by PDO wrapper. One of my tests is an integration test that proves that the abstraction layer produces the right syntax, or binds PDOStatement in the right way, etc. For this, I use an in-memory SQLite database, and declare ext-pdo_sqlite as a dev-dependency of my project.
When Github Actions runs a build, dependencies all get installed, hinting that pdo_sqlite is present on the system. This is further confirmed by the fact that the connection succeeds. However, when I run an insert query to set up my database, I get the following error:
PDOException: SQLSTATE[HY000]: General error: 1 no such column: TRUE
The query looks like this:
INSERT INTO `persons` (`id`, `name`, `dob`, `weight`, `is_dev`, `teeth`) VALUES (NULL, 'Anton', '1987-11-03', 71.3, TRUE, 31)
Table creation is done with PDO like this:
$pdo->exec("CREATE TABLE `$tableName` (`id` int(6) PRIMARY KEY, `name` varchar(255), `dob` datetime, `weight` float(5), `is_dev` bool, `teeth` int(2))");
This only manifests on CI, and local tests pass fine - even on the same PHP version as CI.
Any ideas? Am I just missing something in the syntax? Could it be that GH Actions has only a dummy implementation of SQLite or something?
Note: This is an open source project, and you can see everything, including the failing build, in dhii/pdo-query#1.

How to load Northwind into SQLite3 -- Error 'File is not a database'

I am trying to load the Northwind.Sqlite3.create.sql hosted on https://github.com/jpwhite3/northwind-SQLite3 into SQLite3 on Ubuntu.
I have tried using: sqlite3 Northwind.Sqlite3.create.sql to import the database.
However when I try to view the data using SELECT * FROM CUSTOMERS; I get an error saying Error: file is not a database
Any suggestions as to how to open the database file and use it?
That's just a text file full of DDL statements, not a sqlite3 database. You'd have to import it into a database with something like
sqlite3 mydatabase.db < Northwind.Sqlite3.create.sql

How to vacuum sqlite database?

I want to know how to vacuum sqlite database.
I tried a syntax MANUAL VACUUM command for the whole database from command prompt:
$sqlite3 database_name "VACUUM;";
But it's giving error as:
near "database_name": syntax error.
and also AUTO VACUUM:
PRAGMA auto_vacuum = INCREMENTAL;
And tried it for a particular table as:
VACUUM table_name;
But no result.
You don't to specify the table name in the syntax. Only VACUUM works.
Also, it will clean the main database only and not any attached database files.
For more info, refer to the SQLite documentation.
Give the command like this:
$sqlite3 database_name 'VACUUM;'
As a matter of fact, this is the way to do also other queries from command line:
$sqlite3 database_name 'select * from tablename;'
You can use the full path to the db:
$sqlite3 /path/to/db/foo.db 'VACUUM;'
Run the command:
VACUUM;
if you use DB Browser for Sqlite or
open Sqlite from command prompt:
cd C:\your_folder
C:\Users\your_user\AppData\Local\Android\Sdk\platform-tools\sqlite3.exe -line your_db_name.db
and run
VACUUM;

Resources