summaryrefslogtreecommitdiffstats
path: root/languages/sql/sqlsupport_part.cpp
blob: f61c6bea2aeccafb2a5b9534ae7644388f45cad9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
#include "sqlsupport_part.h"
#include <tqwhatsthis.h>
#include <tqstringlist.h>
#include <tqtimer.h>
#include <tqsqldatabase.h>
#include <tqsqlrecord.h>

#include <kapplication.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kdevgenericfactory.h>
#include <kdebug.h>
#include <tdeaction.h>
#include <tdeparts/part.h>
#include <kdialogbase.h>
#include <tdetexteditor/editinterface.h>
#include <kmessagebox.h>

#include "kdevcore.h"
#include "kdevmainwindow.h"
#include "kdevlanguagesupport.h"
#include "kdevpartcontroller.h"
#include "kdevproject.h"
#include "codemodel.h"
#include "kdevplugininfo.h"

#include "sqlconfigwidget.h"
#include "sqlactions.h"
#include "sqloutputwidget.h"
#include "domutil.h"

typedef KDevGenericFactory<SQLSupportPart> SQLSupportFactory;
static const KDevPluginInfo data("kdevsqlsupport");
K_EXPORT_COMPONENT_FACTORY( libkdevsqlsupport, SQLSupportFactory( data ) )

SQLSupportPart::SQLSupportPart( TQObject *parent, const char *name, const TQStringList& )
        : KDevLanguageSupport ( &data, parent, name ? name : "SQLSupportPart" )
{
    setInstance( SQLSupportFactory::instance() );
    setXMLFile( "kdevsqlsupport.rc" );

    TDEAction *action;
    action = new TDEAction( i18n( "&Run" ), "exec", Key_F9, this, TQT_SLOT( slotRun() ), actionCollection(), "build_execute" );
    action->setToolTip(i18n("Run"));
    action->setWhatsThis(i18n("<b>Run</b><p>Executes a SQL script."));

    dbAction = new SqlListAction( this, i18n( "&Database Connections" ), 0, this, TQT_SLOT(activeConnectionChanged()), actionCollection(), "connection_combo" );

    kdDebug( 9000 ) << "Creating SQLSupportPart" << endl;

    connect( core(), TQT_SIGNAL( projectConfigWidget( KDialogBase* ) ),
             this, TQT_SLOT( projectConfigWidget( KDialogBase* ) ) );
    connect( core(), TQT_SIGNAL(projectOpened()), this, TQT_SLOT(projectOpened()) );
    connect( core(), TQT_SIGNAL(projectClosed()), this, TQT_SLOT(projectClosed()) );
    connect( core(), TQT_SIGNAL(languageChanged()), this, TQT_SLOT(projectOpened()) );
    connect( partController(), TQT_SIGNAL( savedFile( const KURL& ) ), this, TQT_SLOT( savedFile( const KURL& ) ) );

    m_widget = new SqlOutputWidget();
    mainWindow()->embedOutputView( m_widget, i18n( "SQL" ), i18n( "Output of SQL commands" ) );
    TQWhatsThis::add(m_widget, i18n("<b>Output of SQL commands</b><p>This window shows the output of SQL commands being executed. It can display results of SQL \"select\" commands in a table."));
}


SQLSupportPart::~SQLSupportPart()
{
    mainWindow()->removeView(m_widget);
    delete m_widget;
}

TQString SQLSupportPart::cryptStr(const TQString& aStr)
{
    TQString result;
    for (unsigned int i = 0; i < aStr.length(); i++)
	result += (aStr[i].unicode() < 0x20) ? aStr[i] :
		  TQChar(0x1001F - aStr[i].unicode());
    return result;
}

void SQLSupportPart::activeConnectionChanged()
{
    updateCatalog();
}

void SQLSupportPart::clearConfig()
{
    for ( TQStringList::Iterator it = conNames.begin(); it != conNames.end(); ++it ) {
        if ( TQSqlDatabase::contains( *it ) ) {
            TQSqlDatabase::database( *it, false )->close();
            TQSqlDatabase::removeDatabase( *it );
        } else {
            kdDebug( 9000 ) << "Could not find connection named " << (*it) << endl;
        }
    }
    conNames.clear();

    dbAction->refresh();
}

void SQLSupportPart::loadConfig()
{
    clearConfig();

    TQDomDocument* doc = projectDom();

    TQStringList db;
    int i = 0;
    TQString conName;
    while ( true ) {
        TQStringList sdb = DomUtil::readListEntry( *doc, "kdevsqlsupport/servers/server" + TQString::number( i ), "el" );
        if ( (int)sdb.size() < 6 )
            break;

        conName = "KDEVSQLSUPPORT_";
        conName += TQString::number( i );
        conNames << conName;
	TQSqlDatabase* db = TQSqlDatabase::addDatabase( sdb[0], TQString( "KDEVSQLSUPPORT_%1" ).arg( i ) );
        db->setDatabaseName( sdb[1] );
        db->setHostName( sdb[2] );
        bool ok;
        int port = sdb[3].toInt( &ok );
        if ( ok )
            db->setPort( port );
        db->setUserName( sdb[4] );
        db->setPassword( cryptStr( sdb[5] ) );
        db->open();

        i++;
    }

    dbAction->refresh();
}

void SQLSupportPart::projectConfigWidget( KDialogBase *dlg )
{
    TQVBox *vbox = dlg->addVBoxPage( TQString( "SQL" ), i18n( "Specify Your Database Connections" ), BarIcon("source", KIcon::SizeMedium) );
    SqlConfigWidget *w = new SqlConfigWidget( (TQWidget*)vbox, "SQL config widget" );
    w->setProjectDom( projectDom() );
    w->loadConfig();
    connect( dlg, TQT_SIGNAL(okClicked()), w, TQT_SLOT(accept()) );
    connect( w, TQT_SIGNAL(newConfigSaved()), this, TQT_SLOT(loadConfig()) );
}

void SQLSupportPart::projectOpened()
{
    connect( project(), TQT_SIGNAL( addedFilesToProject( const TQStringList & ) ),
             this, TQT_SLOT( addedFilesToProject( const TQStringList & ) ) );
    connect( project(), TQT_SIGNAL( removedFilesFromProject( const TQStringList & ) ),
             this, TQT_SLOT( removedFilesFromProject( const TQStringList & ) ) );

    loadConfig();

    // We want to parse only after all components have been
    // properly initialized
    TQTimer::singleShot( 0, this, TQT_SLOT( parse() ) );
}


void SQLSupportPart::projectClosed()
{
    clearConfig();
}

void SQLSupportPart::slotRun ()
{
    TQString cName = dbAction->currentConnectionName();
    if ( cName.isEmpty() ) {
        KMessageBox::sorry( 0, i18n("Please select a valid database connection.") );
        return;
    }

    KTextEditor::EditInterface* doc = dynamic_cast<KTextEditor::EditInterface*>(partController()->activePart());
    if ( !doc )
        return; // show error message?

    mainWindow()->raiseView( m_widget );
    m_widget->showQuery( cName, doc->text() );
}

#if 0
static TQString dbCaption(const TQSqlDatabase* db)
{
    TQString res;
    if (!db)
        return res;
    res = db->driverName();
    res += TQString::fromLatin1("@");
    res += db->hostName();
    if (db->port() >= 0)
        res += TQString::fromLatin1(":") + TQString::number(db->port());
    return res;
}
#endif

void SQLSupportPart::parse()
{
    // @todo
}

void SQLSupportPart::updateCatalog()
{
    if (!project() || !dbAction)
        return;

    codeModel()->wipeout();

    TQString curConnection = dbAction->currentConnectionName();
    if (curConnection.isEmpty()) {
        emit updatedSourceInfo();
        return;
    }

    FileDom dbf = codeModel()->create<FileModel>();
    dbf->setName(dbAction->currentConnectionName());
    TQSqlDatabase *db = TQSqlDatabase::database(dbAction->currentConnectionName(), true);

    // tables are classes and fields are methods
    if (db->isOpen()) {
        TQSqlRecord inf;
        TQStringList tables = db->tables();
        for (TQStringList::Iterator it = tables.begin(); it != tables.end(); ++it) {
            ClassDom dbc = codeModel()->create<ClassModel>();
            dbc->setName(*it);
            inf = db->record(*it);
            for (int i = 0; i < (int)inf.count(); ++i) {
                FunctionDom dbv = codeModel()->create<FunctionModel>();
                dbv->setName(inf.fieldName(i));
                dbv->setResultType(TQVariant::typeToName(inf.field(i)->type()));
                dbc->addFunction(dbv);
            }
            dbf->addClass(dbc);
        }
    }

    codeModel()->addFile(dbf);

    emit updatedSourceInfo();
}

void SQLSupportPart::addedFilesToProject( const TQStringList &fileList )
{
    TQStringList::ConstIterator it;

    for ( it = fileList.begin(); it != fileList.end(); ++it ) {
//        parse( project() ->projectDirectory() + "/" + ( *it ) );
    }

    emit updatedSourceInfo();
}


void SQLSupportPart::removedFilesFromProject( const TQStringList &fileList )
{
    TQStringList::ConstIterator it;

    for ( it = fileList.begin(); it != fileList.end(); ++it ) {
//        classStore() ->removeWithReferences( project() ->projectDirectory() + "/" + ( *it ) );
    }

    emit updatedSourceInfo();
}

void SQLSupportPart::savedFile( const KURL &fileName )
{
    if ( project() ->allFiles().contains( fileName.path().mid ( project() ->projectDirectory().length() + 1 ) ) ) {
//        parse( fileName );
//        emit updatedSourceInfo();
    }
}

KDevLanguageSupport::Features SQLSupportPart::features()
{
    return Features( Classes | Functions );
}

KMimeType::List SQLSupportPart::mimeTypes( )
{
    KMimeType::List list;
    KMimeType::Ptr mime = KMimeType::mimeType( "text/plain" );
    if( mime )
        list << mime;
    return list;
}

#include "sqlsupport_part.moc"