Subversion Repository Public Repository

litesoft

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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
// This Source Code is in the Public Domain per: http://litesoft.org/License.txt
package org.litesoft.sql;

import org.litesoft.commonfoundation.base.*;
import org.litesoft.commonfoundation.typeutils.Objects;
import org.litesoft.db.*;
import org.litesoft.logger.*;
import org.litesoft.orsup.base.*;
import org.litesoft.orsup.nonpublic.*;
import org.litesoft.orsup.selection.*;
import org.litesoft.sql.statements.*;

import java.sql.*;
import java.util.*;

public class SQLPersistenceHelper extends AbstractPersistenceHelper
{
    public static final Logger LOGGER = LoggerFactory.getLogger( SQLPersistenceHelper.class );

    private SQLDBconnectionProvider mSQLDBconnectionProvider;

    public SQLPersistenceHelper( SQLDBconnectionProvider pSQLDBconnectionProvider )
    {
        Objects.assertNotNull( "SQLDBconnectionProvider", mSQLDBconnectionProvider = pSQLDBconnectionProvider );
    }

    public SQLDBconnectionProvider getSQLDBconnectionProvider()
    {
        return mSQLDBconnectionProvider;
    }

    private SQLDBconnection createSQLDBconnection()
            throws DBException
    {
        return mSQLDBconnectionProvider.createSQLDBconnection();
    }

    private SQLProductSpecificHelper mHelper;

    public SQLProductSpecificHelper getHelper()
    {
        return mHelper;
    }

    // PersistenceHelper vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv

    @Override
    public synchronized void initializeDB()
    {
        SQLDBconnection zDBC = null;
        try
        {
            zDBC = createSQLDBconnection();
            DBinfo info = zDBC.getDBinfo();
            mHelper = SQLProductSpecificHelperManager.getVendorSpecificHelperFor( info );
            mHelper.initializeDB( zDBC.getConnection(), info, new MyIndexColumnsLocator() );
        }
        catch ( Exception e )
        {
            throw new Error( "Unable to initializeDB", e );
        }
        finally
        {
            if ( zDBC != null )
            {
                zDBC.dispose();
            }
        }
    }

    @Override
    public DBconnection createConnection()
            throws DBException
    {
        return createSQLDBconnection();
    }

    @Override
    protected String LLnormalizeIdentifierNotNullOrEmpty( String pIdentifier )
    {
        return getHelper().normalizeIdentifier( pIdentifier );
    }

    @Override
    protected String[] LLgetTablesEquals( String pName )
    {
        return LLgetTablesFor( SQLHelper.escapePercent( pName ) );
    }

    @Override
    protected String[] LLgetTablesStartsWith( String pStart )
    {
        return LLgetTablesFor( SQLHelper.escapePercent( pStart ) + "%" );
    }

    @Override
    protected String[] LLgetTablesEndsWith( String pEnd )
    {
        return LLgetTablesFor( "%" + SQLHelper.escapePercent( pEnd ) );
    }

    @Override
    protected String[] LLgetTablesStartsAndEndsWith( String pStart, String pEnd )
    {
        return LLgetTablesFor( SQLHelper.escapePercent( pStart ) + "%" + SQLHelper.escapePercent( pEnd ) );
    }

    @Override
    protected String[] LLgetTablesForParts( String[] pParts )
    {
        StringBuilder sb = new StringBuilder();
        sb.append( SQLHelper.escapePercent( pParts[0] ) );
        for ( int i = 1; i < pParts.length; i++ )
        {
            sb.append( "%" ).append( SQLHelper.escapePercent( pParts[i] ) );
        }
        return LLgetTablesFor( sb.toString() );
    }

    protected String[] LLgetTablesFor( String pPattern )
    {
        String zPattern = SQLHelper.escapeUnderscore( pPattern );
        SQLDBconnection zDBC = createSQLDBconnection();
        try
        {
            return getHelper().getTablesFor( zDBC.getConnection(), zDBC.getDBinfo(), zPattern );
        }
        catch ( SQLException e )
        {
            throw new WrappedSQLException( e );
        }
        finally
        {
            zDBC.dispose();
        }
    }

    @Override
    protected Map<String, DBtableColumn[]> LLgetColumns( String pTableName )
            throws DBException
    {
        String zTableName = SQLHelper.escapeTableNamePattern( pTableName );
        SQLDBconnection zDBC = createSQLDBconnection();
        try
        {
            return getHelper().getColumns( zDBC.getConnection(), zDBC.getDBinfo(), zTableName );
        }
        catch ( SQLException e )
        {
            throw new WrappedSQLException( e );
        }
        finally
        {
            zDBC.dispose();
        }
    }

    @Override
    protected Map<String, DBtableIndex[]> LLgetIndexes( String pTableName )
            throws DBException
    {
        SQLDBconnection zDBC = createSQLDBconnection();
        try
        {
            return getHelper().getIndexes( zDBC.getConnection(), zDBC.getDBinfo(), pTableName );
        }
        catch ( SQLException e )
        {
            throw new WrappedSQLException( e );
        }
        finally
        {
            zDBC.dispose();
        }
    }

    /**
     * @return TRUE if table exists,
     *         FALSE if table appears to not exist
     */
    @Override
    public boolean tableExists( SimpleFromIdentifier pSimpleFromIdentifier )
            throws DBException, MultipleTablesException
    {
        String zTableName = getHelper().normalizeIdentifier( pSimpleFromIdentifier.getTableName() );

        try
        {
            return LLtableExists( zTableName );
        }
        catch ( SQLException e )
        {
            throw new WrappedSQLException( e );
        }
    }

    /**
     * @return TRUE if table exists,
     *         FALSE if table appears to not exist
     */
    @Override
    public boolean columnExists( SimpleFromIdentifier pSimpleFromIdentifier, String pColumnName )
            throws DBException, MultipleTablesException
    {
        String zTableName = getHelper().normalizeIdentifier( pSimpleFromIdentifier.getTableName() );

        SQLDBconnection dbc = createSQLDBconnection();
        try
        {
            return getHelper().columnExists( dbc.getConnection(), dbc.getDBinfo(), zTableName, pColumnName );
        }
        catch ( SQLException e )
        {
            throw new WrappedSQLException( e );
        }
        finally
        {
            dbc.dispose();
        }
    }

    @Override
    public long rawCount( SimpleFromIdentifier pSimpleFromIdentifier, WhereClause pSelectionWhereClause )
            throws DBException
    {
        String zTableName = getHelper().normalizeIdentifier( pSimpleFromIdentifier.getTableName() );

        return rawCount( zTableName, SQL_OR_Helper.toSQL( pSelectionWhereClause ) );
    }

    @Override
    public void deleteRows( SimpleFromIdentifier pSimpleFromIdentifier, WhereClause pSelectionWhereClause )
            throws DBException
    {
        deleteRows( null, pSimpleFromIdentifier, pSelectionWhereClause );
    }

    @Override
    public void deleteRows( DBconnection pDBconnection, SimpleFromIdentifier pSimpleFromIdentifier, WhereClause pSelectionWhereClause )
            throws DBException
    {

        LLdeleteRows( pDBconnection, createDeleteRowsCmd( pSimpleFromIdentifier, pSelectionWhereClause ) );
    }

    /**
     * @param pSimpleFromIdentifier - Normally the Table Identifier
     * @param pKeyCD                - The Unique Key Column of the table
     * @param pSnagCD               - The Snag Column of the table
     * @param pUniqueSnagValue      - The Unique Value for the Snag Column, that if set will be unique in the table
     * @param pSelectionWhereClause - null means all, which will only succeed if the table only has one entry
     * @param pOrderBy              - null means order immaterial
     * @param pUpdateValuePairs     - additional columns to set
     *
     * @return true if row 'snaged'
     *
     * @throws DBException - Exception regarding the OR layer
     */
    @Override
    public boolean snagOne( SimpleFromIdentifier pSimpleFromIdentifier, SimpleColumnDefinition pKeyCD, SimpleColumnDefinition pSnagCD, Long pUniqueSnagValue, WhereClause pSelectionWhereClause, OrderBy pOrderBy, ColumnUpdateValuePair[] pUpdateValuePairs )
            throws DBException
    {
        String zTableName = getHelper().normalizeIdentifier( pSimpleFromIdentifier.getTableName() );

        String zSelectColumns = pKeyCD.getColumnName();

        WhereClause zNullSnagColumn = WhereClauseFactory.INSTANCE.isNull( pSnagCD );

        DBconnection zDBconnection = createConnection();
        try
        {
            String wc = (pSelectionWhereClause == null) ? zNullSnagColumn.toSQL() : WhereClauseFactory.INSTANCE.and( zNullSnagColumn, pSelectionWhereClause ).toSQL();
            String orderBy = (pOrderBy != null) ? pOrderBy.toSQL() : new OrderBy( pKeyCD ).toSQL();
            String zSubSelect = getHelper().buildQuery( zDBconnection.getDBinfo().getProductVersion(), //
                                                        zTableName, zSelectColumns, wc, orderBy, 0, 1 );

            StringBuilder zUpdateClause = new StringBuilder();
            zUpdateClause.append( pSnagCD.getColumnName() ).append( '=' );
            WhereClauseColumnSupport.makeSqlValue( zUpdateClause, pSnagCD, false, pUniqueSnagValue );
            for ( ColumnUpdateValuePair zPair : pUpdateValuePairs )
            {
                if ( zPair != null )
                {
                    SimpleColumnDefinition zSCD = zPair.getColumnDefinition();
                    zUpdateClause.append( ", " ).append( zSCD.getColumnName() ).append( '=' );
                    WhereClauseColumnSupport.makeSqlValue( zUpdateClause, zSCD, false, zPair.getValue() );
                }
            }

            StringBuilder zWC = new StringBuilder( "WHERE " );
            zWC.append( pKeyCD.getColumnName() ).append( " in (" ).append( zSubSelect ).append( ')' );

            String cmd = createUpdateCmd( zTableName, zUpdateClause.toString(), zWC.toString() );
            int rowsEffected = update( zDBconnection, cmd, true );
            if ( rowsEffected > 1 )
            {
                throw new MultiRowUpdateException( cmd, rowsEffected );
            }
            return rowsEffected == 1;
        }
        finally
        {
            zDBconnection.dispose();
        }
        //    create table SnagTest
        //    (
        //      id bigint NOT NULL,
        //      recordversion bigint NOT NULL,
        //      claimedby bigint,
        //      zsnaguniquecolumn bigint,
        //      description character varying,
        //      started boolean NOT NULL,
        //      CONSTRAINT SnagTest_pk PRIMARY KEY (id)
        //    );
        //
        //    UPDATE SnagTest SET zsnaguniquecolumn=22 where id in (
        //    select id from SnagTest where zsnaguniquecolumn is null order by id limit 1 );
    }

    @Override
    public void deleteAllRows( SimpleFromIdentifier pSimpleFromIdentifier )
            throws DBException
    {
        deleteAllRows( null, pSimpleFromIdentifier );
    }

    @Override
    public void deleteAllRows( DBconnection pDBconnection, SimpleFromIdentifier pSimpleFromIdentifier )
            throws DBException
    {
        String zTableName = getHelper().normalizeIdentifier( pSimpleFromIdentifier.getTableName() );

        LLdeleteRows( pDBconnection, "DELETE FROM " + zTableName + " WHERE 1=1" );
    }

    @Override
    public void dropTable( TableManager pTableManager, SimpleFromIdentifier pSimpleFromIdentifier )
            throws DBException
    {
        String zTableName = getHelper().normalizeIdentifier( pSimpleFromIdentifier.getTableName() );

        String cmd = "DROP TABLE " + zTableName;
        try
        {
            executeNoResultsNoCommitSQL( cmd );
            pTableManager.removeTable( zTableName );
            return;
        }
        catch ( DBException e )
        {
            try
            {
                if ( LLtableExists( zTableName ) )
                {
                    LOGGER.error.log( e, "Failed to drop table (HSQLDB has no 'IF EXISTS' clause in 'DROP TABLE': ", zTableName );
                    throw e; // table exists, so original 'DROP' problem should be reported
                }
            }
            catch ( SQLException e1 )
            {
                throw e; // unable to ask if table exists, so original 'DROP' problem should be reported
            }
        }
        // Here means that the table 'probably' does NOT exist
        pTableManager.removeTable( zTableName );
    }

    @Override
    public void addColumnToExistingTable( SimpleFromIdentifier pSimpleFromIdentifier, SimpleColumnDefinitionExtended pSCD )
            throws DBException
    {
        String zTableName = getHelper().normalizeIdentifier( pSimpleFromIdentifier.getTableName() );

        StringBuilder cmd = new StringBuilder();
        cmd.append( "ALTER TABLE " ).append( zTableName ).append( " ADD ( " );

        createTableColumn( cmd, pSCD );
        String zCmd = cmd.append( " )" ).toString();
        executeNoResultsNoCommitSQL( zCmd );
    }

    // PersistenceHelper ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    protected void createTableColumn( StringBuilder pCmd, SimpleColumnDefinitionExtended pSCD )
    {
        createTableColumn( pCmd, pSCD.getColumnName(), pSCD );

        if ( pSCD.hasSearchColumn() )
        {
            pCmd.append( ", " );
            createTableColumn( pCmd, pSCD.getSearchColumnName(), pSCD );
        }
    }

    private void createTableColumn( StringBuilder pCmd, String pColumnName, SimpleColumnDefinitionExtended pSCD )
    {
        pCmd.append( pColumnName );
        pCmd.append( ' ' );
        getHelper().addColumnType( pCmd, pSCD );
        if ( pSCD.isRequired() )
        {
            pCmd.append( " NOT NULL" );
        }
    }

    private void LLdeleteRows( DBconnection pDBconnection, String pCmd )
    {
        if ( pDBconnection == null )
        {
            new JDBCexecuteNoResults( this, pCmd, this ).executeSQLnoResults( true );
        }
        else
        {
            JDBCexecuteUpdate updater = new JDBCexecuteUpdate( this, pDBconnection, pCmd, this );
            try
            {
                updater.executeUpdate( false );
            }
            finally
            {
                updater.dispose();
            }
        }
    }

    protected int update( DBconnection pDBconnection, String pCmd, boolean pCommit )
            throws DBException
    {

        JDBCexecuteUpdate updater = new JDBCexecuteUpdate( this, pDBconnection, pCmd, this );
        try
        {
            return updater.executeUpdate( pCommit );
        }
        finally
        {
            updater.dispose();
        }
    }

    protected String createUpdateCmd( String pTableName, String pUpdateClause, String pWhereClause )
    {
        return "UPDATE " + pTableName + " SET " + pUpdateClause + " " + pWhereClause;
    }

    private String createDeleteRowsCmd( SimpleFromIdentifier pSimpleFromIdentifier, WhereClause pSelectionWhereClause )
    {
        String zTableName = getHelper().normalizeIdentifier( pSimpleFromIdentifier.getTableName() );

        String zCmd = "DELETE FROM " + zTableName;
        if ( pSelectionWhereClause != null )
        {
            zCmd += " " + pSelectionWhereClause.toSQL();
        }
        return zCmd;
    }

    protected long rawCount( String pTableName, String pWhereClause )
            throws DBException
    {
        // todo: switch the '*' to the primary key!
        JDBCexecuteQuery query = new JDBCexecuteQuery( this, "SELECT COUNT(*) FROM " + pTableName + " " + pWhereClause, this ).executeQuery();
        try
        {
            if ( !query.hasNext() )
            {
                throw new SQLException( "No Results returned" );
            }
            long count = query.next().getLong( 1 );
            if ( query.hasNext() )
            {
                throw new SQLException( "Too many result rows, expected only 1" );
            }
            return count;
        }
        catch ( SQLException e )
        {
            throw query.error( e );
        }
        finally
        {
            query.dispose();
        }
    }

    private boolean LLtableExists( String pTableName )
            throws SQLException, MultipleTablesException
    {
        SQLDBconnection zDBC = createSQLDBconnection();
        try
        {
            return getHelper().tableExists( zDBC.getConnection(), zDBC.getDBinfo(), pTableName );
        }
        finally
        {
            zDBC.dispose();
        }
    }

    protected void executeNoResultsNoCommitSQL( String pCmd )
    {
        new JDBCexecuteNoResults( this, pCmd, this ).executeSQLnoResults( false );
    }

    protected static class MyRowSource implements PersistenceHelperRowSource
    {
        private JDBCexecuteQuery mQuery;
        private int mResultSetColumnCount = -1;

        public MyRowSource( SQLPersistenceHelper pPersistenceHelper, String pCmd, DBconnection pDBconnection )
        {
            mQuery = new JDBCexecuteQuery( pPersistenceHelper, pCmd, this );
            try
            {
                mQuery.assumeOwnershipOf( pDBconnection );
            }
            catch ( RuntimeException e )
            {
                dispose();
                throw e;
            }
        }

        @Override
        public PersistenceHelperRowSource prepareForGetNextRow()
        {
            if ( mResultSetColumnCount != -1 )
            {
                throw new IllegalStateException( "Multiple calls to prepareForGetNextRow()" );
            }
            try
            {
                mQuery.executeQuery();
                mResultSetColumnCount = mQuery.getResultSetColumnCount();
                return this;
            }
            catch ( RuntimeException e )
            {
                dispose();
                throw e;
            }
        }

        @Override
        public Object[] getNextRow()
        {
            if ( mQuery == null )
            {
                return null;
            }
            try
            {
                if ( !mQuery.hasNext() )
                {
                    dispose();
                    return null;
                }
                Object[] row = new Object[mResultSetColumnCount];
                try
                {
                    ResultSet rs = mQuery.next();
                    for ( int i = 0; i < row.length; i++ )
                    {
                        row[i] = rs.getObject( i + 1 );
                    }
                }
                catch ( SQLException e )
                {
                    dispose();
                    throw new WrappedSQLException( e );
                }
                return row;
            }
            catch ( RuntimeException e )
            {
                dispose();
                throw e;
            }
        }

        @Override
        public void dispose()
        {
            if ( mQuery != null )
            {
                mQuery.dispose();
                mQuery = null;
            }
        }

        @Override
        protected void finalize()
                throws Throwable
        {
            dispose();
            super.finalize();
        }
    }

    //private boolean indexDefinitionIsUpToDate( MetaDataForPO pMetaDataForPO, MetaDataForPO.Index pIndex )
    //        throws ORMapperException
    //{
    //    List<String> metadataColumns = Arrays.asList( pIndex.getColumns() );
    //    Collections.sort( metadataColumns );
    //    List<String> existingColumns = getIndexColumns( pMetaDataForPO.getTableName(), pIndex.getIndexName() );
    //    Collections.sort( existingColumns );
    //    return existingColumns.equals( metadataColumns );
    //}

    private static class MyIndexColumnsLocator implements SQLIndexColumnsLocator
    {
        @Override
        public String[] getColumnsForIndex( String pIndexName )
        {
            for ( MetaDataForPO zMD : DataStoreLocator.get().getMetaDataStore().getAllMetaDataForPOs() )
            {
                for ( MetaDataForPO.Index zIndex : zMD.getIndexes() )
                {
                    if ( pIndexName.equalsIgnoreCase( zIndex.getIndexName() ) )
                    {
                        List<String> rv = new ArrayList<String>();
                        for ( String zColumn : zIndex.getColumns() )
                        {
                            if ( zColumn.endsWith( "_id" ) )
                            {
                                zColumn = zColumn.substring( 0, zColumn.length() - 3 );
                            }
                            rv.add( DeCamelizer.resolve( zColumn ) );
                        }
                        return rv.toArray( new String[rv.size()] );
                    }
                }
            }
            return null;
        }
    }
}

Commits for litesoft/trunk/Java/core/Server/src/org/litesoft/sql/SQLPersistenceHelper.java

Diff revisions: vs.
Revision Author Commited Message
942 Diff Diff GeorgeS picture GeorgeS Mon 02 Jun, 2014 23:41:46 +0000

Extracting commonfoundation

939 Diff Diff GeorgeS picture GeorgeS Mon 02 Jun, 2014 21:30:31 +0000

Extracting commonfoundation

917 Diff Diff GeorgeS picture GeorgeS Sun 08 Dec, 2013 20:49:56 +0000

1.7 prep & VersionedStaticContentFilter upgrade to new “/ver” model!

804 Diff Diff GeorgeS picture GeorgeS Wed 15 Aug, 2012 12:48:51 +0000
151 Diff Diff GeorgeS picture GeorgeS Thu 17 Mar, 2011 04:16:22 +0000
85 Diff Diff GeorgeS picture GeorgeS Wed 24 Nov, 2010 21:07:10 +0000
49 Diff Diff GeorgeS picture GeorgeS Mon 12 Apr, 2010 02:59:10 +0000

License Text

24 Diff Diff GeorgeS picture GeorgeS Wed 24 Feb, 2010 01:51:38 +0000
2 GeorgeS picture GeorgeS Sun 07 Feb, 2010 12:50:58 +0000