Skip to content

Instantly share code, notes, and snippets.

@drouarb
Created January 7, 2019 20:18
Show Gist options
  • Select an option

  • Save drouarb/8f628f870fbd2e65db89a6cb0cc8a4e0 to your computer and use it in GitHub Desktop.

Select an option

Save drouarb/8f628f870fbd2e65db89a6cb0cc8a4e0 to your computer and use it in GitHub Desktop.
#!/bin/bash
if [ $# -le 0 ]
then
echo "Usage: $0 <db_to_fix.db>"
exit 1
fi
tofix=$1
cols=`sqlite3 "$tofix" << GETAUTOINC
WITH RECURSIVE
a AS (
SELECT name, lower(replace(replace(sql, char(13), ' '), char(10), ' ')) AS sql
FROM sqlite_master
WHERE lower(sql) LIKE '%integer% autoincrement%'
),
b AS (
SELECT name, trim(substr(sql, instr(sql, '(') + 1)) AS sql
FROM a
),
c AS (
SELECT b.name, sql, '' AS col
FROM b
UNION ALL
SELECT
c.name,
trim(substr(c.sql, ifnull(nullif(instr(c.sql, ','), 0), instr(c.sql, ')')) + 1)) AS sql,
trim(substr(c.sql, 1, ifnull(nullif(instr(c.sql, ','), 0), instr(c.sql, ')')) - 1)) AS col
FROM c JOIN b ON c.name = b.name
WHERE c.sql != ''
),
d AS (
SELECT name, substr(col, 1, instr(col, ' ') - 1) AS col
FROM c
WHERE col LIKE '%autoincrement%'
)
SELECT name
FROM d
ORDER BY name, col;
GETAUTOINC`
for table in $cols
do
if [ `sqlite3 "$tofix" <<< "SELECT * FROM sqlite_sequence WHERE name = '$table';" | wc -l` -eq 0 ]
then
echo "Table $table isn't initialized in sqlite_sequence, fixing..."
sqlite3 "$tofix" <<< "INSERT INTO sqlite_sequence (name,seq) VALUES ('$table', 1);"
echo "OK"
else
echo "Table $table OK"
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment