Skysnake

SQLite Alter Table Drop Column (with some AutoIt magic)

1 post in this topic

#1 ·  Posted (edited)

#cs ----------------------------------------------------------------------------

    AutoIt Version: 3.3.14.0
    Author:         Skysnake
    Date:           2016.05.17

    Script Function:
    Alter table drop column.

    By way of example the original table has these three columns:
    name,surname,nickname
    to be replaced with
    name,surname,number

    "We cannot drop a specific column in SQLite 3. See the FAQ. It is not possible to
    rename a column, remove a column, or add or remove constraints from a table.
    While you can always create a new table and then drop the older one.Dec 9, 2011"

    http://stackoverflow.com/questions/8442147/how-to-delete-or-add-column-in-sqlite


    The only ALTER TABLE functions that SQLite supports are those that can be
    accomplished without having to rewrite the entire table.  Or, to put it
    another way, the only ALTER TABLE functions supported are those that can be
    done in O(1) time.

    ALTER TABLE DROP COLUMN requires writing every row of the table.

    D. Richard Hipp

    http://sqlite.1065341.n5.nabble.com/Why-can-t-SQLite-drop-columns-td64687.html

    Notes:
    Required original array size of table to be altered (zero count +1)
    Required the name of the column to drop
    Required full "create table ..." syntax for new column eg: , number  text   not null default 'Contact Number')


#ce ----------------------------------------------------------------------------

; Script Start - Add your code below here
; SQLite.dll version must match

#include <Array.au3>
#include <MsgBoxConstants.au3>
#include <SQLite.au3>
#include <SQLite.dll.au3>

Local Const $iMax = 6 ; this is the current table column count
Local $query, $aResult, $iRows, $iColumns, $ColName, $sMsg, $mySQLdb, $aLessColmns[$iMax][1] ; will require only one column
Local $sNewColNames


Local $sLocalSQLiteDll = "sqlite3_win32-x86-3120100.dll" ;

Local $sSQliteDll = _SQLite_Startup($sLocalSQLiteDll, False, 1)
If @error Then
    MsgBox($MB_SYSTEMMODAL, "SQLite Error", "SQLite3.dll Can't be Loaded!" & @CRLF & @CRLF & _
            "Not FOUND in @SystemDir, @WindowsDir, @ScriptDir, @WorkingDir or from www.autoitscript.com")
    Exit -1
EndIf

ConsoleWrite("_SQLite_LibVersion=" & _SQLite_LibVersion() & @CRLF)
$mySQLdb = _SQLite_Open(@ScriptDir & '\mydb.sql3')


; Without $sCallback it's a resultless statement
; ..................................................... create table tORiginal for System Info
$query = "CREATE TABLE if not exists tORiginal ( " _
         & "id  integer primary     key         unique not null " _
         & ", name                  text        not null default 'First Name' " _
         & ", surname               text        not null default 'Surname' " _
         & ", nickname              text        not null default 'Nickname' " _
         & ", RegDate               text        NOT NULL DEFAULT current_timestamp " _
         & " ) ; "

If Not _SQLite_Exec($mySQLdb, $query) = $SQLITE_OK Then _
        MsgBox($MB_SYSTEMMODAL, "SQLite Error", _SQLite_ErrMsg() & " * " & @ScriptLineNumber)

ConsoleWrite("SQL created tORiginal " & @CRLF)



; Without $sCallback it's a resultless statement
; ..................................................... create table tORiginal for System Info
$query = "Insert into tORiginal (name,surname,nickname) values ('John','Jones','Johnny') " _
         & "  ; "

If Not _SQLite_Exec($mySQLdb, $query) = $SQLITE_OK Then _
        MsgBox($MB_SYSTEMMODAL, "SQLite Error", _SQLite_ErrMsg() & " * " & @ScriptLineNumber)

ConsoleWrite("SQL data inserted into tORiginal " & @CRLF)



$query = " SELECT * FROM tORiginal " _
         & " ; "
; Query
; Query
$iRval = _SQLite_GetTable2d($mySQLdb, $query, $aResult, $iRows, $iColumns)
If $iRval = $SQLITE_OK Then
    ConsoleWrite("$SQLITE_OK at Line " & $SQLITE_OK & " " &@ScriptLineNumber & @CRLF)
Else
    MsgBox($MB_SYSTEMMODAL, "SQLite Error: " & $iRval, _SQLite_ErrMsg())
EndIf

_ArrayDisplay($aResult, "CREATEd and INSERTed"  ) ; show the results of insert into SQL table

; https://www.sqlite.org/pragma.html#pragma_table_info
$query = " pragma table_info(tORiginal) " _
         & " ; "
; Query
; Query
$iRval = _SQLite_GetTable2d($mySQLdb, $query, $aResult, $iRows, $iColumns)
If $iRval = $SQLITE_OK Then
    ConsoleWrite("$SQLITE_OK at Line " & $SQLITE_OK & " " &@ScriptLineNumber & @CRLF)
Else
    MsgBox($MB_SYSTEMMODAL, "SQLite Error: " & $iRval, _SQLite_ErrMsg())
EndIf

_ArrayDisplay($aResult, "Pragma Result: Original Table") ; show the results of pragma

ConsoleWrite("SQL PRAGMA to find all columns " & @CRLF)

; this is the AutoIt magic
; SQLite does not allow manipulation of the pragma result, but
; AutoIt can process this result as normal query result
; delete column %id% from result
#cs
    Row|Col 0   |Col 1      |Col 2  |Col 3  |Col 4      |Col 5
    [0]|cid     |name       |type   |notnull|dflt_value |pk
    [1]|0       |id         |INTEGER|0      |           |1
    [2]|1       |Name       |       |0      |           |0
    [3]|2       |Surname    |       |0      |           |0
    [4]|3       |Nickname   |       |0      |           |0 ; >>>>>>>>> column to remove

#CE

;https://www.autoitscript.com/wiki/Arrays#Comparing_Arrays
Local $transfound = UBound($aResult, 1) - 1
For $i = 1 To $transfound Step +1
    ConsoleWrite($aResult[$i][1] & @CRLF)

    ; Check that the array is big enough
    If UBound($aLessColmns) = $i Then
        ; Resize the array when $i is equal to the element count in the array to prevent subscript error
        ReDim $aLessColmns[$aLessColmns[0] + $iMax]

    EndIf

    If StringRegExp($aResult[$i][1], "nick") Then ;>>>>>>>>> remove the column you dont want
        ; it may be dangerous to use a Regex here :)
        ; do nothing, do not add this column name
    Else
        $aLessColmns[$i][0] = $aResult[$i][1] ; safely add data to new index element

        $aLessColmns[0][0] = $i ; update the index count for future reference
    EndIf
Next

; for good measure
; Move backwards through the array deleting the blank lines
For $i = UBound($aLessColmns) - 1 To 0 Step -1
    If $aLessColmns[$i][0] = "" Then
        _ArrayDelete($aLessColmns, $i)
    EndIf
Next
$aLessColmns[0][0] = UBound($aLessColmns) - 1 ; update the index count for future reference

_ArrayDisplay($aLessColmns, "Column names from tORiginal less one") ; show the new array

$sNewColNames = _ArrayToString($aLessColmns, "|", 1, -1, ",") ; entire array
MsgBox(0, "$sNewColNames", $sNewColNames)
ConsoleWrite("New Column names " & $sNewColNames & @CRLF)
; now create a transient table, insert values, and rename

_SQLite_Exec($mySQLdb, "Create table tNewColumns (" & $sNewColNames & ", number             text        not null default 'Contact Number') ; " & _
        "Insert into tNewColumns (" & $sNewColNames & ") select " & $sNewColNames & " from  tORiginal " & _
        " ; ")


$query = " SELECT * FROM tNewColumns " _
         & " ; "
; Query
; Query
$iRval = _SQLite_GetTable2d($mySQLdb, $query, $aResult, $iRows, $iColumns)
If $iRval = $SQLITE_OK Then
    ConsoleWrite("$SQLITE_OK at Line " & $SQLITE_OK & @ScriptLineNumber & @CRLF)
Else
    MsgBox($MB_SYSTEMMODAL, "SQLite Error: " & $iRval, _SQLite_ErrMsg())
EndIf

_ArrayDisplay($aResult, "Results of new table") ; show the results of insert into SQL table

; https://www.sqlite.org/pragma.html#pragma_table_info
$query = " pragma table_info(tORiginal) " _
         & " ; "
; Query
; Query
$iRval = _SQLite_GetTable2d($mySQLdb, $query, $aResult, $iRows, $iColumns)
If $iRval = $SQLITE_OK Then
    ConsoleWrite("$SQLITE_OK at Line " & $SQLITE_OK & " " &@ScriptLineNumber & @CRLF)
Else
    MsgBox($MB_SYSTEMMODAL, "SQLite Error: " & $iRval, _SQLite_ErrMsg())
EndIf

_ArrayDisplay($aResult, "Pragma Result: altered Original Table") ; show the results of pragma

ConsoleWrite("SQL PRAGMA to find all columns " & @CRLF)


; now drop tORiginal
; https://www.sqlite.org/lang_altertable.html
; ALTER TABLE tNewColumns RENAME TO tORiginal


ConsoleWrite("_SQLite_Shutdown " & @CRLF)
_SQLite_Shutdown()
FileDelete($mySQLdb)

I believe it is suitable to post on this Forum, as it serves no purpose anywhere else.  I have searched, and except for some ancient threads referring to this, could find nothing similar.  

I used SQLite 3.12.1 which can be downloaded here Precompiled Binaries for Windows. I see they are up to 3.12.2 now.

Painfully obvious is of course that one must know the name of the offending column. :)

 

Edited by Skysnake
2016.06.04 Improved

Skysnake

Why is the snake in the sky?

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now

  • Similar Content

    • AdamUL
      By AdamUL
      I have been testing AutoIt 3.3.14.3 with SQLite, and the Help File examples.  The examples that I have tested are throwing errors or not doing anything.  I have sqlite3.dll, sqlite3_x64.dll, and sqlite3.exe in the directories with the testing script.  I am copying the examples directly from the help file into a test script for testing with no edits.  The _SQLite_GetTable2d example is returning an error ("Library used incorrectly") with each _SQLite_Exec command.  The _SQLite_FastEncode example returns an empty dialog box.  The _SQLite_Exec example only prints out the SQLite version, and nothing else in the SciTE console.  Currently, I'm still searching for what is causing this issue.  I'm on Windows 7 Enterprise 64-bit.  Is anyone else having this issue?  
       
      Adam
       
    • Burgs
      By Burgs
      Greetings,
        I have SQLite setup within my AutoIT program...I'm trying to accomplish what should be a relatively simple task.  I want to be able to return an array of 'table' names for an established database...I believe this might be possible using the '_SQLite_SQLiteExe' command...since it seems to be able to access SQLite schemas...?  The ".tables" command is one of them...if I am not mistaken that command returns a list of all table names in the active database.
        I am attempting the following:
      #include <SQLite.au3> #include <SQLite.dll.au3> Global $hDb, $sIn, $sOut ... $sIn = ".tables" & @CRLF _SQLite_SQLiteExe($hDb, $sIn, $sOut) if @error == 0 Then ;Show Table (using SQLite3.dll) Else if @error == 2 Then ConsoleWrite("ERROR: Sqlite3.exe file not found" & @CRLF) Else ConsoleWrite("ERROR: @error=" & @error & " when calling _SQLite_SQLiteExe" & @CRLF) EndIf ;@error is "2"...OR NOT... EndIf ;@error is "0"...OR NOT... ...   The error being thrown is "ERROR: Sqlite3.exe file not found" ...
        Am I required to have the Sqlite3.exe installed in my directory (i.e. @ScriptsDir)...???  I do not have it in there at present because I did not believe it was necessary with the 'include' calls to "SQLite.au3" and "SQLite.dll.au3"...any advice appreciated.  Thanks in advance. 
      Regards
       
       
       
       
       
       
       
    • FrancescoDiMuro
      By FrancescoDiMuro
      Good evening guys
      I am working on a little project, in which I have to retrieve 8000+ rows of data from a table, from a SQLite database, to populate a combobox 
      This is what I tried 'til now, but it still takes about 12 seconds to populate the combobox.
      _SQLite_Exec($objDatabase, "BEGIN TRANSACTION;") If _SQLite_GetTable($objDatabase, "SELECT DISTINCT Comune FROM LISTA_COMUNI;", $arrRisultatoQuery, $intRighe, $intColonne) = $SQLITE_OK Then For $i = 2 To UBound($arrRisultatoQuery) - 1 If $i < UBound($arrRisultatoQuery) - 1 Then GUICtrlSetData($cbo_ComuneNascita, $arrRisultatoQuery[$i] & "|") Else GUICtrlSetData($cbo_ComuneNascita, $arrRisultatoQuery[$i]) EndIf Next _SQLite_Exec($objDatabase, "COMMIT;") Are there any other solution to retrieve 8000+ records from a SQLite database?
      Thank you very much  
    • FrancescoDiMuro
      By FrancescoDiMuro
      Good morning community!
      I am working on a script which read from a text file ( .txt ) and should import all the content in a SQLite3 DB, in order to execute some queries that should be difficult to execute on a text file.
      So, I was looking for something very very fast, because the file could be very large ( I don't know exaclty how much can became big, but I know a lot of rows, it's a log file ... )
      I found the "Import method", but I don't know If I can implement it in a query ( @jchd, it's your turn!  )
      Do you know some methods that I can implement in my script to have a very very fast import of thousands and thousands rows in a SQLite3 DB?
      Thanks a lot
      Francesco
    • FrancescoDiMuro
      By FrancescoDiMuro
      Good morning guys
      I was trying to use again SQLite in AutoIt, and I've again an issue: I can't startup SQLite...
      Can you please show me the way to set the enviornment for a SQLIte usage in AutoIt? Step by step, I'll follow your suggestion(s).

      Thanks for everyone will reply!

      Francesco