msi: Use ordering information to update the correct row.
[wine.git] / dlls / msi / table.c
blob80fe3ee51f3423f1d39e992188505d47b5907d13
1 /*
2 * Implementation of the Microsoft Installer (msi.dll)
4 * Copyright 2002-2005 Mike McCormack for CodeWeavers
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #include <stdarg.h>
22 #include <assert.h>
24 #define COBJMACROS
25 #define NONAMELESSUNION
26 #define NONAMELESSSTRUCT
28 #include "windef.h"
29 #include "winbase.h"
30 #include "winerror.h"
31 #include "msi.h"
32 #include "msiquery.h"
33 #include "objbase.h"
34 #include "objidl.h"
35 #include "winnls.h"
36 #include "msipriv.h"
37 #include "query.h"
39 #include "wine/debug.h"
40 #include "wine/unicode.h"
42 WINE_DEFAULT_DEBUG_CHANNEL(msidb);
44 #define MSITABLE_HASH_TABLE_SIZE 37
46 typedef struct tagMSICOLUMNHASHENTRY
48 struct tagMSICOLUMNHASHENTRY *next;
49 UINT value;
50 UINT row;
51 } MSICOLUMNHASHENTRY;
53 typedef struct tagMSICOLUMNINFO
55 LPWSTR tablename;
56 UINT number;
57 LPWSTR colname;
58 UINT type;
59 UINT offset;
60 INT ref_count;
61 BOOL temporary;
62 MSICOLUMNHASHENTRY **hash_table;
63 } MSICOLUMNINFO;
65 typedef struct tagMSIORDERINFO
67 UINT *reorder;
68 UINT num_cols;
69 UINT cols[1];
70 } MSIORDERINFO;
72 struct tagMSITABLE
74 BYTE **data;
75 BOOL *data_persistent;
76 UINT row_count;
77 struct list entry;
78 MSICOLUMNINFO *colinfo;
79 UINT col_count;
80 MSICONDITION persistent;
81 INT ref_count;
82 WCHAR name[1];
85 static const WCHAR szStringData[] = {
86 '_','S','t','r','i','n','g','D','a','t','a',0 };
87 static const WCHAR szStringPool[] = {
88 '_','S','t','r','i','n','g','P','o','o','l',0 };
90 /* information for default tables */
91 static WCHAR szTables[] = { '_','T','a','b','l','e','s',0 };
92 static WCHAR szTable[] = { 'T','a','b','l','e',0 };
93 static WCHAR szName[] = { 'N','a','m','e',0 };
94 static WCHAR szColumns[] = { '_','C','o','l','u','m','n','s',0 };
95 static WCHAR szNumber[] = { 'N','u','m','b','e','r',0 };
96 static WCHAR szType[] = { 'T','y','p','e',0 };
98 static const MSICOLUMNINFO _Columns_cols[4] = {
99 { szColumns, 1, szTable, MSITYPE_VALID | MSITYPE_STRING | MSITYPE_KEY | 64, 0, 0, 0, NULL },
100 { szColumns, 2, szNumber, MSITYPE_VALID | MSITYPE_KEY | 2, 2, 0, 0, NULL },
101 { szColumns, 3, szName, MSITYPE_VALID | MSITYPE_STRING | 64, 4, 0, 0, NULL },
102 { szColumns, 4, szType, MSITYPE_VALID | 2, 6, 0, 0, NULL },
105 static const MSICOLUMNINFO _Tables_cols[1] = {
106 { szTables, 1, szName, MSITYPE_VALID | MSITYPE_STRING | MSITYPE_KEY | 64, 0, 0, 0, NULL },
109 #define MAX_STREAM_NAME 0x1f
111 static UINT table_get_column_info( MSIDATABASE *db, LPCWSTR name,
112 MSICOLUMNINFO **pcols, UINT *pcount );
113 static void table_calc_column_offsets( MSIDATABASE *db, MSICOLUMNINFO *colinfo,
114 DWORD count );
115 static UINT get_tablecolumns( MSIDATABASE *db,
116 LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz);
117 static void msi_free_colinfo( MSICOLUMNINFO *colinfo, UINT count );
119 static inline UINT bytes_per_column( MSIDATABASE *db, const MSICOLUMNINFO *col, UINT bytes_per_strref )
121 if( MSITYPE_IS_BINARY(col->type) )
122 return 2;
124 if( col->type & MSITYPE_STRING )
125 return bytes_per_strref;
127 if( (col->type & 0xff) <= 2)
128 return 2;
130 if( (col->type & 0xff) != 4 )
131 ERR("Invalid column size!\n");
133 return 4;
136 static int utf2mime(int x)
138 if( (x>='0') && (x<='9') )
139 return x-'0';
140 if( (x>='A') && (x<='Z') )
141 return x-'A'+10;
142 if( (x>='a') && (x<='z') )
143 return x-'a'+10+26;
144 if( x=='.' )
145 return 10+26+26;
146 if( x=='_' )
147 return 10+26+26+1;
148 return -1;
151 LPWSTR encode_streamname(BOOL bTable, LPCWSTR in)
153 DWORD count = MAX_STREAM_NAME;
154 DWORD ch, next;
155 LPWSTR out, p;
157 if( !bTable )
158 count = lstrlenW( in )+2;
159 if (!(out = msi_alloc( count*sizeof(WCHAR) ))) return NULL;
160 p = out;
162 if( bTable )
164 *p++ = 0x4840;
165 count --;
167 while( count -- )
169 ch = *in++;
170 if( !ch )
172 *p = ch;
173 return out;
175 if( ( ch < 0x80 ) && ( utf2mime(ch) >= 0 ) )
177 ch = utf2mime(ch) + 0x4800;
178 next = *in;
179 if( next && (next<0x80) )
181 next = utf2mime(next);
182 if( next != -1 )
184 next += 0x3ffffc0;
185 ch += (next<<6);
186 in++;
190 *p++ = ch;
192 ERR("Failed to encode stream name (%s)\n",debugstr_w(in));
193 msi_free( out );
194 return NULL;
197 static int mime2utf(int x)
199 if( x<10 )
200 return x + '0';
201 if( x<(10+26))
202 return x - 10 + 'A';
203 if( x<(10+26+26))
204 return x - 10 - 26 + 'a';
205 if( x == (10+26+26) )
206 return '.';
207 return '_';
210 BOOL decode_streamname(LPCWSTR in, LPWSTR out)
212 WCHAR ch;
213 DWORD count = 0;
215 while ( (ch = *in++) )
217 if( (ch >= 0x3800 ) && (ch < 0x4840 ) )
219 if( ch >= 0x4800 )
220 ch = mime2utf(ch-0x4800);
221 else
223 ch -= 0x3800;
224 *out++ = mime2utf(ch&0x3f);
225 count++;
226 ch = mime2utf((ch>>6)&0x3f);
229 *out++ = ch;
230 count++;
232 *out = 0;
233 return count;
236 void enum_stream_names( IStorage *stg )
238 IEnumSTATSTG *stgenum = NULL;
239 HRESULT r;
240 STATSTG stat;
241 ULONG n, count;
242 WCHAR name[0x40];
244 r = IStorage_EnumElements( stg, 0, NULL, 0, &stgenum );
245 if( FAILED( r ) )
246 return;
248 n = 0;
249 while( 1 )
251 count = 0;
252 r = IEnumSTATSTG_Next( stgenum, 1, &stat, &count );
253 if( FAILED( r ) || !count )
254 break;
255 decode_streamname( stat.pwcsName, name );
256 TRACE("stream %2d -> %s %s\n", n,
257 debugstr_w(stat.pwcsName), debugstr_w(name) );
258 CoTaskMemFree( stat.pwcsName );
259 n++;
262 IEnumSTATSTG_Release( stgenum );
265 UINT read_stream_data( IStorage *stg, LPCWSTR stname, BOOL table,
266 BYTE **pdata, UINT *psz )
268 HRESULT r;
269 UINT ret = ERROR_FUNCTION_FAILED;
270 VOID *data;
271 ULONG sz, count;
272 IStream *stm = NULL;
273 STATSTG stat;
274 LPWSTR encname;
276 encname = encode_streamname(table, stname);
278 TRACE("%s -> %s\n",debugstr_w(stname),debugstr_w(encname));
280 r = IStorage_OpenStream(stg, encname, NULL,
281 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &stm);
282 msi_free( encname );
283 if( FAILED( r ) )
285 WARN("open stream failed r = %08x - empty table?\n", r);
286 return ret;
289 r = IStream_Stat(stm, &stat, STATFLAG_NONAME );
290 if( FAILED( r ) )
292 WARN("open stream failed r = %08x!\n", r);
293 goto end;
296 if( stat.cbSize.QuadPart >> 32 )
298 WARN("Too big!\n");
299 goto end;
302 sz = stat.cbSize.QuadPart;
303 data = msi_alloc( sz );
304 if( !data )
306 WARN("couldn't allocate memory r=%08x!\n", r);
307 ret = ERROR_NOT_ENOUGH_MEMORY;
308 goto end;
311 r = IStream_Read(stm, data, sz, &count );
312 if( FAILED( r ) || ( count != sz ) )
314 msi_free( data );
315 WARN("read stream failed r = %08x!\n", r);
316 goto end;
319 *pdata = data;
320 *psz = sz;
321 ret = ERROR_SUCCESS;
323 end:
324 IStream_Release( stm );
326 return ret;
329 UINT write_stream_data( IStorage *stg, LPCWSTR stname,
330 LPCVOID data, UINT sz, BOOL bTable )
332 HRESULT r;
333 UINT ret = ERROR_FUNCTION_FAILED;
334 ULONG count;
335 IStream *stm = NULL;
336 ULARGE_INTEGER size;
337 LARGE_INTEGER pos;
338 LPWSTR encname;
340 encname = encode_streamname(bTable, stname );
341 r = IStorage_OpenStream( stg, encname, NULL,
342 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, &stm);
343 if( FAILED(r) )
345 r = IStorage_CreateStream( stg, encname,
346 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &stm);
348 msi_free( encname );
349 if( FAILED( r ) )
351 WARN("open stream failed r = %08x\n", r);
352 return ret;
355 size.QuadPart = sz;
356 r = IStream_SetSize( stm, size );
357 if( FAILED( r ) )
359 WARN("Failed to SetSize\n");
360 goto end;
363 pos.QuadPart = 0;
364 r = IStream_Seek( stm, pos, STREAM_SEEK_SET, NULL );
365 if( FAILED( r ) )
367 WARN("Failed to Seek\n");
368 goto end;
371 if (sz)
373 r = IStream_Write(stm, data, sz, &count );
374 if( FAILED( r ) || ( count != sz ) )
376 WARN("Failed to Write\n");
377 goto end;
381 ret = ERROR_SUCCESS;
383 end:
384 IStream_Release( stm );
386 return ret;
389 static void free_table( MSITABLE *table )
391 UINT i;
392 for( i=0; i<table->row_count; i++ )
393 msi_free( table->data[i] );
394 msi_free( table->data );
395 msi_free( table->data_persistent );
396 msi_free_colinfo( table->colinfo, table->col_count );
397 msi_free( table->colinfo );
398 msi_free( table );
401 static UINT msi_table_get_row_size( MSIDATABASE *db, const MSICOLUMNINFO *cols, UINT count, UINT bytes_per_strref )
403 const MSICOLUMNINFO *last_col;
405 if (!count)
406 return 0;
408 if (bytes_per_strref != LONG_STR_BYTES)
410 UINT i, size = 0;
411 for (i = 0; i < count; i++) size += bytes_per_column( db, &cols[i], bytes_per_strref );
412 return size;
414 last_col = &cols[count - 1];
415 return last_col->offset + bytes_per_column( db, last_col, bytes_per_strref );
418 /* add this table to the list of cached tables in the database */
419 static UINT read_table_from_storage( MSIDATABASE *db, MSITABLE *t, IStorage *stg )
421 BYTE *rawdata = NULL;
422 UINT rawsize = 0, i, j, row_size, row_size_mem;
424 TRACE("%s\n",debugstr_w(t->name));
426 row_size = msi_table_get_row_size( db, t->colinfo, t->col_count, db->bytes_per_strref );
427 row_size_mem = msi_table_get_row_size( db, t->colinfo, t->col_count, LONG_STR_BYTES );
429 /* if we can't read the table, just assume that it's empty */
430 read_stream_data( stg, t->name, TRUE, &rawdata, &rawsize );
431 if( !rawdata )
432 return ERROR_SUCCESS;
434 TRACE("Read %d bytes\n", rawsize );
436 if( rawsize % row_size )
438 WARN("Table size is invalid %d/%d\n", rawsize, row_size );
439 goto err;
442 t->row_count = rawsize / row_size;
443 t->data = msi_alloc_zero( t->row_count * sizeof (USHORT*) );
444 if( !t->data )
445 goto err;
446 t->data_persistent = msi_alloc_zero( t->row_count * sizeof(BOOL));
447 if ( !t->data_persistent )
448 goto err;
450 /* transpose all the data */
451 TRACE("Transposing data from %d rows\n", t->row_count );
452 for (i = 0; i < t->row_count; i++)
454 UINT ofs = 0, ofs_mem = 0;
456 t->data[i] = msi_alloc( row_size_mem );
457 if( !t->data[i] )
458 goto err;
459 t->data_persistent[i] = TRUE;
461 for (j = 0; j < t->col_count; j++)
463 UINT m = bytes_per_column( db, &t->colinfo[j], LONG_STR_BYTES );
464 UINT n = bytes_per_column( db, &t->colinfo[j], db->bytes_per_strref );
465 UINT k;
467 if ( n != 2 && n != 3 && n != 4 )
469 ERR("oops - unknown column width %d\n", n);
470 goto err;
472 if (t->colinfo[j].type & MSITYPE_STRING && n < m)
474 for (k = 0; k < m; k++)
476 if (k < n)
477 t->data[i][ofs_mem + k] = rawdata[ofs * t->row_count + i * n + k];
478 else
479 t->data[i][ofs_mem + k] = 0;
482 else
484 for (k = 0; k < n; k++)
485 t->data[i][ofs_mem + k] = rawdata[ofs * t->row_count + i * n + k];
487 ofs_mem += m;
488 ofs += n;
492 msi_free( rawdata );
493 return ERROR_SUCCESS;
494 err:
495 msi_free( rawdata );
496 return ERROR_FUNCTION_FAILED;
499 void free_cached_tables( MSIDATABASE *db )
501 while( !list_empty( &db->tables ) )
503 MSITABLE *t = LIST_ENTRY( list_head( &db->tables ), MSITABLE, entry );
505 list_remove( &t->entry );
506 free_table( t );
510 static MSITABLE *find_cached_table( MSIDATABASE *db, LPCWSTR name )
512 MSITABLE *t;
514 LIST_FOR_EACH_ENTRY( t, &db->tables, MSITABLE, entry )
515 if( !strcmpW( name, t->name ) )
516 return t;
518 return NULL;
521 static UINT table_get_column_info( MSIDATABASE *db, LPCWSTR name, MSICOLUMNINFO **pcols, UINT *pcount )
523 UINT r, column_count = 0;
524 MSICOLUMNINFO *columns;
526 /* get the number of columns in this table */
527 column_count = 0;
528 r = get_tablecolumns( db, name, NULL, &column_count );
529 if( r != ERROR_SUCCESS )
530 return r;
532 *pcount = column_count;
534 /* if there's no columns, there's no table */
535 if( column_count == 0 )
536 return ERROR_INVALID_PARAMETER;
538 TRACE("Table %s found\n", debugstr_w(name) );
540 columns = msi_alloc( column_count*sizeof (MSICOLUMNINFO) );
541 if( !columns )
542 return ERROR_FUNCTION_FAILED;
544 r = get_tablecolumns( db, name, columns, &column_count );
545 if( r != ERROR_SUCCESS )
547 msi_free( columns );
548 return ERROR_FUNCTION_FAILED;
551 *pcols = columns;
553 return r;
556 UINT msi_create_table( MSIDATABASE *db, LPCWSTR name, column_info *col_info,
557 MSICONDITION persistent, MSITABLE **table_ret)
559 UINT r, nField;
560 MSIVIEW *tv = NULL;
561 MSIRECORD *rec = NULL;
562 column_info *col;
563 MSITABLE *table;
564 UINT i;
566 /* only add tables that don't exist already */
567 if( TABLE_Exists(db, name ) )
569 WARN("table %s exists\n", debugstr_w(name));
570 return ERROR_BAD_QUERY_SYNTAX;
573 table = msi_alloc( sizeof (MSITABLE) + lstrlenW(name)*sizeof (WCHAR) );
574 if( !table )
575 return ERROR_FUNCTION_FAILED;
577 table->ref_count = 1;
578 table->row_count = 0;
579 table->data = NULL;
580 table->data_persistent = NULL;
581 table->colinfo = NULL;
582 table->col_count = 0;
583 table->persistent = persistent;
584 lstrcpyW( table->name, name );
586 for( col = col_info; col; col = col->next )
587 table->col_count++;
589 table->colinfo = msi_alloc( table->col_count * sizeof(MSICOLUMNINFO) );
590 if (!table->colinfo)
592 free_table( table );
593 return ERROR_FUNCTION_FAILED;
596 for( i = 0, col = col_info; col; i++, col = col->next )
598 table->colinfo[ i ].tablename = strdupW( col->table );
599 table->colinfo[ i ].number = i + 1;
600 table->colinfo[ i ].colname = strdupW( col->column );
601 table->colinfo[ i ].type = col->type;
602 table->colinfo[ i ].offset = 0;
603 table->colinfo[ i ].ref_count = 0;
604 table->colinfo[ i ].hash_table = NULL;
605 table->colinfo[ i ].temporary = col->temporary;
607 table_calc_column_offsets( db, table->colinfo, table->col_count);
609 r = TABLE_CreateView( db, szTables, &tv );
610 TRACE("CreateView returned %x\n", r);
611 if( r )
613 free_table( table );
614 return r;
617 r = tv->ops->execute( tv, 0 );
618 TRACE("tv execute returned %x\n", r);
619 if( r )
620 goto err;
622 rec = MSI_CreateRecord( 1 );
623 if( !rec )
624 goto err;
626 r = MSI_RecordSetStringW( rec, 1, name );
627 if( r )
628 goto err;
630 r = tv->ops->insert_row( tv, rec, -1, persistent == MSICONDITION_FALSE );
631 TRACE("insert_row returned %x\n", r);
632 if( r )
633 goto err;
635 tv->ops->delete( tv );
636 tv = NULL;
638 msiobj_release( &rec->hdr );
639 rec = NULL;
641 if( persistent != MSICONDITION_FALSE )
643 /* add each column to the _Columns table */
644 r = TABLE_CreateView( db, szColumns, &tv );
645 if( r )
646 return r;
648 r = tv->ops->execute( tv, 0 );
649 TRACE("tv execute returned %x\n", r);
650 if( r )
651 goto err;
653 rec = MSI_CreateRecord( 4 );
654 if( !rec )
655 goto err;
657 r = MSI_RecordSetStringW( rec, 1, name );
658 if( r )
659 goto err;
662 * need to set the table, column number, col name and type
663 * for each column we enter in the table
665 nField = 1;
666 for( col = col_info; col; col = col->next )
668 r = MSI_RecordSetInteger( rec, 2, nField );
669 if( r )
670 goto err;
672 r = MSI_RecordSetStringW( rec, 3, col->column );
673 if( r )
674 goto err;
676 r = MSI_RecordSetInteger( rec, 4, col->type );
677 if( r )
678 goto err;
680 r = tv->ops->insert_row( tv, rec, -1, FALSE );
681 if( r )
682 goto err;
684 nField++;
686 if( !col )
687 r = ERROR_SUCCESS;
690 err:
691 if (rec)
692 msiobj_release( &rec->hdr );
693 /* FIXME: remove values from the string table on error */
694 if( tv )
695 tv->ops->delete( tv );
697 if (r == ERROR_SUCCESS)
699 list_add_head( &db->tables, &table->entry );
700 *table_ret = table;
702 else
703 free_table( table );
705 return r;
708 static UINT get_table( MSIDATABASE *db, LPCWSTR name, MSITABLE **table_ret )
710 MSITABLE *table;
711 UINT r;
713 /* first, see if the table is cached */
714 table = find_cached_table( db, name );
715 if( table )
717 *table_ret = table;
718 return ERROR_SUCCESS;
721 /* nonexistent tables should be interpreted as empty tables */
722 table = msi_alloc( sizeof (MSITABLE) + lstrlenW(name)*sizeof (WCHAR) );
723 if( !table )
724 return ERROR_FUNCTION_FAILED;
726 table->row_count = 0;
727 table->data = NULL;
728 table->data_persistent = NULL;
729 table->colinfo = NULL;
730 table->col_count = 0;
731 table->persistent = MSICONDITION_TRUE;
732 lstrcpyW( table->name, name );
734 if ( !strcmpW( name, szTables ) || !strcmpW( name, szColumns ) )
735 table->persistent = MSICONDITION_NONE;
737 r = table_get_column_info( db, name, &table->colinfo, &table->col_count);
738 if (r != ERROR_SUCCESS)
740 free_table ( table );
741 return r;
744 r = read_table_from_storage( db, table, db->storage );
745 if( r != ERROR_SUCCESS )
747 free_table( table );
748 return r;
751 list_add_head( &db->tables, &table->entry );
752 *table_ret = table;
753 return ERROR_SUCCESS;
756 static UINT read_table_int(BYTE *const *data, UINT row, UINT col, UINT bytes)
758 UINT ret = 0, i;
760 for (i = 0; i < bytes; i++)
761 ret += data[row][col + i] << i * 8;
763 return ret;
766 static UINT save_table( MSIDATABASE *db, const MSITABLE *t, UINT bytes_per_strref )
768 BYTE *rawdata = NULL;
769 UINT rawsize, i, j, row_size, row_count;
770 UINT r = ERROR_FUNCTION_FAILED;
772 /* Nothing to do for non-persistent tables */
773 if( t->persistent == MSICONDITION_FALSE )
774 return ERROR_SUCCESS;
776 TRACE("Saving %s\n", debugstr_w( t->name ) );
778 row_size = msi_table_get_row_size( db, t->colinfo, t->col_count, bytes_per_strref );
779 row_count = t->row_count;
780 for (i = 0; i < t->row_count; i++)
782 if (!t->data_persistent[i])
784 row_count = 1; /* yes, this is bizarre */
785 break;
788 rawsize = row_count * row_size;
789 rawdata = msi_alloc_zero( rawsize );
790 if( !rawdata )
792 r = ERROR_NOT_ENOUGH_MEMORY;
793 goto err;
796 rawsize = 0;
797 for (i = 0; i < t->row_count; i++)
799 UINT ofs = 0, ofs_mem = 0;
801 if (!t->data_persistent[i]) break;
803 for (j = 0; j < t->col_count; j++)
805 UINT m = bytes_per_column( db, &t->colinfo[j], LONG_STR_BYTES );
806 UINT n = bytes_per_column( db, &t->colinfo[j], bytes_per_strref );
807 UINT k;
809 if (n != 2 && n != 3 && n != 4)
811 ERR("oops - unknown column width %d\n", n);
812 goto err;
814 if (t->colinfo[j].type & MSITYPE_STRING && n < m)
816 UINT id = read_table_int( t->data, i, ofs_mem, LONG_STR_BYTES );
817 if (id > 1 << bytes_per_strref * 8)
819 ERR("string id %u out of range\n", id);
820 goto err;
823 for (k = 0; k < n; k++)
825 rawdata[ofs * row_count + i * n + k] = t->data[i][ofs_mem + k];
827 ofs_mem += m;
828 ofs += n;
830 rawsize += row_size;
833 TRACE("writing %d bytes\n", rawsize);
834 r = write_stream_data( db->storage, t->name, rawdata, rawsize, TRUE );
836 err:
837 msi_free( rawdata );
838 return r;
841 static void table_calc_column_offsets( MSIDATABASE *db, MSICOLUMNINFO *colinfo, DWORD count )
843 DWORD i;
845 for( i=0; colinfo && (i<count); i++ )
847 assert( (i+1) == colinfo[ i ].number );
848 if (i)
849 colinfo[i].offset = colinfo[ i - 1 ].offset
850 + bytes_per_column( db, &colinfo[ i - 1 ], LONG_STR_BYTES );
851 else
852 colinfo[i].offset = 0;
853 TRACE("column %d is [%s] with type %08x ofs %d\n",
854 colinfo[i].number, debugstr_w(colinfo[i].colname),
855 colinfo[i].type, colinfo[i].offset);
859 static UINT get_defaulttablecolumns( MSIDATABASE *db, LPCWSTR name,
860 MSICOLUMNINFO *colinfo, UINT *sz)
862 const MSICOLUMNINFO *p;
863 DWORD i, n;
865 TRACE("%s\n", debugstr_w(name));
867 if (!strcmpW( name, szTables ))
869 p = _Tables_cols;
870 n = 1;
872 else if (!strcmpW( name, szColumns ))
874 p = _Columns_cols;
875 n = 4;
877 else
878 return ERROR_FUNCTION_FAILED;
880 /* duplicate the string data so we can free it in msi_free_colinfo */
881 for (i=0; i<n; i++)
883 if (colinfo && (i < *sz) )
885 colinfo[i] = p[i];
886 colinfo[i].tablename = strdupW( p[i].tablename );
887 colinfo[i].colname = strdupW( p[i].colname );
889 if( colinfo && (i >= *sz) )
890 break;
892 table_calc_column_offsets( db, colinfo, n );
893 *sz = n;
894 return ERROR_SUCCESS;
897 static void msi_free_colinfo( MSICOLUMNINFO *colinfo, UINT count )
899 UINT i;
901 for( i=0; i<count; i++ )
903 msi_free( colinfo[i].tablename );
904 msi_free( colinfo[i].colname );
905 msi_free( colinfo[i].hash_table );
909 static LPWSTR msi_makestring( const MSIDATABASE *db, UINT stringid)
911 return strdupW(msi_string_lookup_id( db->strings, stringid ));
914 static UINT get_tablecolumns( MSIDATABASE *db,
915 LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz)
917 UINT r, i, n=0, table_id, count, maxcount = *sz;
918 MSITABLE *table = NULL;
920 TRACE("%s\n", debugstr_w(szTableName));
922 /* first check if there is a default table with that name */
923 r = get_defaulttablecolumns( db, szTableName, colinfo, sz );
924 if( ( r == ERROR_SUCCESS ) && *sz )
925 return r;
927 r = get_table( db, szColumns, &table );
928 if( r != ERROR_SUCCESS )
930 ERR("couldn't load _Columns table\n");
931 return ERROR_FUNCTION_FAILED;
934 /* convert table and column names to IDs from the string table */
935 r = msi_string2idW( db->strings, szTableName, &table_id );
936 if( r != ERROR_SUCCESS )
938 WARN("Couldn't find id for %s\n", debugstr_w(szTableName));
939 return r;
942 TRACE("Table id is %d, row count is %d\n", table_id, table->row_count);
944 /* Note: _Columns table doesn't have non-persistent data */
946 /* if maxcount is non-zero, assume it's exactly right for this table */
947 memset( colinfo, 0, maxcount*sizeof(*colinfo) );
948 count = table->row_count;
949 for( i=0; i<count; i++ )
951 if( read_table_int(table->data, i, 0, LONG_STR_BYTES) != table_id )
952 continue;
953 if( colinfo )
955 UINT id = read_table_int(table->data, i, table->colinfo[2].offset, LONG_STR_BYTES);
956 UINT col = read_table_int(table->data, i, table->colinfo[1].offset, sizeof(USHORT)) - (1<<15);
958 /* check the column number is in range */
959 if (col<1 || col>maxcount)
961 ERR("column %d out of range\n", col);
962 continue;
965 /* check if this column was already set */
966 if (colinfo[ col - 1 ].number)
968 ERR("duplicate column %d\n", col);
969 continue;
972 colinfo[ col - 1 ].tablename = msi_makestring( db, table_id );
973 colinfo[ col - 1 ].number = col;
974 colinfo[ col - 1 ].colname = msi_makestring( db, id );
975 colinfo[ col - 1 ].type = read_table_int(table->data, i,
976 table->colinfo[3].offset,
977 sizeof(USHORT)) - (1<<15);
978 colinfo[ col - 1 ].offset = 0;
979 colinfo[ col - 1 ].ref_count = 0;
980 colinfo[ col - 1 ].hash_table = NULL;
982 n++;
985 TRACE("%s has %d columns\n", debugstr_w(szTableName), n);
987 if (colinfo && n != maxcount)
989 ERR("missing column in table %s\n", debugstr_w(szTableName));
990 msi_free_colinfo(colinfo, maxcount );
991 return ERROR_FUNCTION_FAILED;
994 table_calc_column_offsets( db, colinfo, n );
995 *sz = n;
997 return ERROR_SUCCESS;
1000 static void msi_update_table_columns( MSIDATABASE *db, LPCWSTR name )
1002 MSITABLE *table;
1003 LPWSTR tablename;
1004 UINT size, offset, old_count;
1005 UINT n;
1007 /* We may free name in msi_free_colinfo. */
1008 tablename = strdupW( name );
1010 table = find_cached_table( db, tablename );
1011 old_count = table->col_count;
1012 msi_free_colinfo( table->colinfo, table->col_count );
1013 msi_free( table->colinfo );
1014 table->colinfo = NULL;
1016 table_get_column_info( db, tablename, &table->colinfo, &table->col_count );
1017 if (!table->col_count)
1018 goto done;
1020 size = msi_table_get_row_size( db, table->colinfo, table->col_count, LONG_STR_BYTES );
1021 offset = table->colinfo[table->col_count - 1].offset;
1023 for ( n = 0; n < table->row_count; n++ )
1025 table->data[n] = msi_realloc( table->data[n], size );
1026 if (old_count < table->col_count)
1027 memset( &table->data[n][offset], 0, size - offset );
1030 done:
1031 msi_free(tablename);
1034 /* try to find the table name in the _Tables table */
1035 BOOL TABLE_Exists( MSIDATABASE *db, LPCWSTR name )
1037 UINT r, table_id, i;
1038 MSITABLE *table;
1040 if( !strcmpW( name, szTables ) || !strcmpW( name, szColumns ) ||
1041 !strcmpW( name, szStreams ) || !strcmpW( name, szStorages ) )
1042 return TRUE;
1044 r = msi_string2idW( db->strings, name, &table_id );
1045 if( r != ERROR_SUCCESS )
1047 TRACE("Couldn't find id for %s\n", debugstr_w(name));
1048 return FALSE;
1051 r = get_table( db, szTables, &table );
1052 if( r != ERROR_SUCCESS )
1054 ERR("table %s not available\n", debugstr_w(szTables));
1055 return FALSE;
1058 for( i = 0; i < table->row_count; i++ )
1060 if( read_table_int( table->data, i, 0, LONG_STR_BYTES ) == table_id )
1061 return TRUE;
1064 return FALSE;
1067 /* below is the query interface to a table */
1069 typedef struct tagMSITABLEVIEW
1071 MSIVIEW view;
1072 MSIDATABASE *db;
1073 MSITABLE *table;
1074 MSICOLUMNINFO *columns;
1075 MSIORDERINFO *order;
1076 UINT num_cols;
1077 UINT row_size;
1078 WCHAR name[1];
1079 } MSITABLEVIEW;
1081 static UINT TABLE_fetch_int( struct tagMSIVIEW *view, UINT row, UINT col, UINT *val )
1083 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1084 UINT offset, n;
1086 if( !tv->table )
1087 return ERROR_INVALID_PARAMETER;
1089 if( (col==0) || (col>tv->num_cols) )
1090 return ERROR_INVALID_PARAMETER;
1092 /* how many rows are there ? */
1093 if( row >= tv->table->row_count )
1094 return ERROR_NO_MORE_ITEMS;
1096 if( tv->columns[col-1].offset >= tv->row_size )
1098 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1099 ERR("%p %p\n", tv, tv->columns );
1100 return ERROR_FUNCTION_FAILED;
1103 if (tv->order)
1104 row = tv->order->reorder[row];
1106 n = bytes_per_column( tv->db, &tv->columns[col - 1], LONG_STR_BYTES );
1107 if (n != 2 && n != 3 && n != 4)
1109 ERR("oops! what is %d bytes per column?\n", n );
1110 return ERROR_FUNCTION_FAILED;
1113 offset = tv->columns[col-1].offset;
1114 *val = read_table_int(tv->table->data, row, offset, n);
1116 /* TRACE("Data [%d][%d] = %d\n", row, col, *val ); */
1118 return ERROR_SUCCESS;
1121 static UINT msi_stream_name( const MSITABLEVIEW *tv, UINT row, LPWSTR *pstname )
1123 LPWSTR p, stname = NULL;
1124 UINT i, r, type, ival;
1125 DWORD len;
1126 LPCWSTR sval;
1127 MSIVIEW *view = (MSIVIEW *) tv;
1129 TRACE("%p %d\n", tv, row);
1131 len = lstrlenW( tv->name ) + 1;
1132 stname = msi_alloc( len*sizeof(WCHAR) );
1133 if ( !stname )
1135 r = ERROR_OUTOFMEMORY;
1136 goto err;
1139 lstrcpyW( stname, tv->name );
1141 for ( i = 0; i < tv->num_cols; i++ )
1143 type = tv->columns[i].type;
1144 if ( type & MSITYPE_KEY )
1146 WCHAR number[0x20];
1148 r = TABLE_fetch_int( view, row, i+1, &ival );
1149 if ( r != ERROR_SUCCESS )
1150 goto err;
1152 if ( tv->columns[i].type & MSITYPE_STRING )
1154 sval = msi_string_lookup_id( tv->db->strings, ival );
1155 if ( !sval )
1157 r = ERROR_INVALID_PARAMETER;
1158 goto err;
1161 else
1163 static const WCHAR fmt[] = { '%','d',0 };
1164 UINT n = bytes_per_column( tv->db, &tv->columns[i], LONG_STR_BYTES );
1166 switch( n )
1168 case 2:
1169 sprintfW( number, fmt, ival-0x8000 );
1170 break;
1171 case 4:
1172 sprintfW( number, fmt, ival^0x80000000 );
1173 break;
1174 default:
1175 ERR( "oops - unknown column width %d\n", n );
1176 r = ERROR_FUNCTION_FAILED;
1177 goto err;
1179 sval = number;
1182 len += lstrlenW( szDot ) + lstrlenW( sval );
1183 p = msi_realloc ( stname, len*sizeof(WCHAR) );
1184 if ( !p )
1186 r = ERROR_OUTOFMEMORY;
1187 goto err;
1189 stname = p;
1191 lstrcatW( stname, szDot );
1192 lstrcatW( stname, sval );
1194 else
1195 continue;
1198 *pstname = stname;
1199 return ERROR_SUCCESS;
1201 err:
1202 msi_free( stname );
1203 *pstname = NULL;
1204 return r;
1208 * We need a special case for streams, as we need to reference column with
1209 * the name of the stream in the same table, and the table name
1210 * which may not be available at higher levels of the query
1212 static UINT TABLE_fetch_stream( struct tagMSIVIEW *view, UINT row, UINT col, IStream **stm )
1214 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1215 UINT r;
1216 LPWSTR encname, full_name = NULL;
1218 if( !view->ops->fetch_int )
1219 return ERROR_INVALID_PARAMETER;
1221 r = msi_stream_name( tv, row, &full_name );
1222 if ( r != ERROR_SUCCESS )
1224 ERR("fetching stream, error = %d\n", r);
1225 return r;
1228 encname = encode_streamname( FALSE, full_name );
1229 r = db_get_raw_stream( tv->db, encname, stm );
1230 if( r )
1231 ERR("fetching stream %s, error = %d\n",debugstr_w(full_name), r);
1233 msi_free( full_name );
1234 msi_free( encname );
1235 return r;
1238 static UINT TABLE_set_int( MSITABLEVIEW *tv, UINT row, UINT col, UINT val )
1240 UINT offset, n, i;
1242 if( !tv->table )
1243 return ERROR_INVALID_PARAMETER;
1245 if( (col==0) || (col>tv->num_cols) )
1246 return ERROR_INVALID_PARAMETER;
1248 if( row >= tv->table->row_count )
1249 return ERROR_INVALID_PARAMETER;
1251 if( tv->columns[col-1].offset >= tv->row_size )
1253 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1254 ERR("%p %p\n", tv, tv->columns );
1255 return ERROR_FUNCTION_FAILED;
1258 msi_free( tv->columns[col-1].hash_table );
1259 tv->columns[col-1].hash_table = NULL;
1261 n = bytes_per_column( tv->db, &tv->columns[col - 1], LONG_STR_BYTES );
1262 if ( n != 2 && n != 3 && n != 4 )
1264 ERR("oops! what is %d bytes per column?\n", n );
1265 return ERROR_FUNCTION_FAILED;
1268 offset = tv->columns[col-1].offset;
1269 for ( i = 0; i < n; i++ )
1270 tv->table->data[row][offset + i] = (val >> i * 8) & 0xff;
1272 return ERROR_SUCCESS;
1275 static UINT TABLE_get_row( struct tagMSIVIEW *view, UINT row, MSIRECORD **rec )
1277 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1279 if (!tv->table)
1280 return ERROR_INVALID_PARAMETER;
1282 if (tv->order)
1283 row = tv->order->reorder[row];
1285 return msi_view_get_row(tv->db, view, row, rec);
1288 static UINT msi_addstreamW( MSIDATABASE *db, LPCWSTR name, IStream *data )
1290 UINT r;
1291 MSIQUERY *query = NULL;
1292 MSIRECORD *rec = NULL;
1294 static const WCHAR insert[] = {
1295 'I','N','S','E','R','T',' ','I','N','T','O',' ',
1296 '`','_','S','t','r','e','a','m','s','`',' ',
1297 '(','`','N','a','m','e','`',',',
1298 '`','D','a','t','a','`',')',' ',
1299 'V','A','L','U','E','S',' ','(','?',',','?',')',0};
1301 TRACE("%p %s %p\n", db, debugstr_w(name), data);
1303 rec = MSI_CreateRecord( 2 );
1304 if ( !rec )
1305 return ERROR_OUTOFMEMORY;
1307 r = MSI_RecordSetStringW( rec, 1, name );
1308 if ( r != ERROR_SUCCESS )
1309 goto err;
1311 r = MSI_RecordSetIStream( rec, 2, data );
1312 if ( r != ERROR_SUCCESS )
1313 goto err;
1315 r = MSI_DatabaseOpenViewW( db, insert, &query );
1316 if ( r != ERROR_SUCCESS )
1317 goto err;
1319 r = MSI_ViewExecute( query, rec );
1321 err:
1322 msiobj_release( &query->hdr );
1323 msiobj_release( &rec->hdr );
1325 return r;
1328 static UINT get_table_value_from_record( MSITABLEVIEW *tv, MSIRECORD *rec, UINT iField, UINT *pvalue )
1330 MSICOLUMNINFO columninfo;
1331 UINT r;
1333 if ( (iField <= 0) ||
1334 (iField > tv->num_cols) ||
1335 MSI_RecordIsNull( rec, iField ) )
1336 return ERROR_FUNCTION_FAILED;
1338 columninfo = tv->columns[ iField - 1 ];
1340 if ( MSITYPE_IS_BINARY(columninfo.type) )
1342 *pvalue = 1; /* refers to the first key column */
1344 else if ( columninfo.type & MSITYPE_STRING )
1346 LPCWSTR sval = MSI_RecordGetString( rec, iField );
1347 if (sval)
1349 r = msi_string2idW(tv->db->strings, sval, pvalue);
1350 if (r != ERROR_SUCCESS)
1351 return ERROR_NOT_FOUND;
1353 else *pvalue = 0;
1355 else if ( bytes_per_column( tv->db, &columninfo, LONG_STR_BYTES ) == 2 )
1357 *pvalue = 0x8000 + MSI_RecordGetInteger( rec, iField );
1358 if ( *pvalue & 0xffff0000 )
1360 ERR("field %u value %d out of range\n", iField, *pvalue - 0x8000);
1361 return ERROR_FUNCTION_FAILED;
1364 else
1366 INT ival = MSI_RecordGetInteger( rec, iField );
1367 *pvalue = ival ^ 0x80000000;
1370 return ERROR_SUCCESS;
1373 static UINT TABLE_set_row( struct tagMSIVIEW *view, UINT row, MSIRECORD *rec, UINT mask )
1375 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1376 UINT i, val, r = ERROR_SUCCESS;
1378 if ( !tv->table )
1379 return ERROR_INVALID_PARAMETER;
1381 /* test if any of the mask bits are invalid */
1382 if ( mask >= (1<<tv->num_cols) )
1383 return ERROR_INVALID_PARAMETER;
1385 for ( i = 0; i < tv->num_cols; i++ )
1387 BOOL persistent;
1389 /* only update the fields specified in the mask */
1390 if ( !(mask&(1<<i)) )
1391 continue;
1393 persistent = (tv->table->persistent != MSICONDITION_FALSE) &&
1394 (tv->table->data_persistent[row]);
1395 /* FIXME: should we allow updating keys? */
1397 val = 0;
1398 if ( !MSI_RecordIsNull( rec, i + 1 ) )
1400 r = get_table_value_from_record (tv, rec, i + 1, &val);
1401 if ( MSITYPE_IS_BINARY(tv->columns[ i ].type) )
1403 IStream *stm;
1404 LPWSTR stname;
1406 if ( r != ERROR_SUCCESS )
1407 return ERROR_FUNCTION_FAILED;
1409 r = MSI_RecordGetIStream( rec, i + 1, &stm );
1410 if ( r != ERROR_SUCCESS )
1411 return r;
1413 r = msi_stream_name( tv, row, &stname );
1414 if ( r != ERROR_SUCCESS )
1416 IStream_Release( stm );
1417 return r;
1420 r = msi_addstreamW( tv->db, stname, stm );
1421 IStream_Release( stm );
1422 msi_free ( stname );
1424 if ( r != ERROR_SUCCESS )
1425 return r;
1427 else if ( tv->columns[i].type & MSITYPE_STRING )
1429 UINT x;
1431 if ( r != ERROR_SUCCESS )
1433 LPCWSTR sval = MSI_RecordGetString( rec, i + 1 );
1434 val = msi_addstringW( tv->db->strings, sval, -1, 1,
1435 persistent ? StringPersistent : StringNonPersistent );
1437 else
1439 TABLE_fetch_int(&tv->view, row, i + 1, &x);
1440 if (val == x)
1441 continue;
1444 else
1446 if ( r != ERROR_SUCCESS )
1447 return ERROR_FUNCTION_FAILED;
1451 r = TABLE_set_int( tv, row, i+1, val );
1452 if ( r != ERROR_SUCCESS )
1453 break;
1455 return r;
1458 static UINT table_create_new_row( struct tagMSIVIEW *view, UINT *num, BOOL temporary )
1460 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1461 BYTE **p, *row;
1462 BOOL *b;
1463 UINT sz;
1464 BYTE ***data_ptr;
1465 BOOL **data_persist_ptr;
1466 UINT *row_count;
1468 TRACE("%p %s\n", view, temporary ? "TRUE" : "FALSE");
1470 if( !tv->table )
1471 return ERROR_INVALID_PARAMETER;
1473 row = msi_alloc_zero( tv->row_size );
1474 if( !row )
1475 return ERROR_NOT_ENOUGH_MEMORY;
1477 row_count = &tv->table->row_count;
1478 data_ptr = &tv->table->data;
1479 data_persist_ptr = &tv->table->data_persistent;
1480 if (*num == -1)
1481 *num = tv->table->row_count;
1483 sz = (*row_count + 1) * sizeof (BYTE*);
1484 if( *data_ptr )
1485 p = msi_realloc( *data_ptr, sz );
1486 else
1487 p = msi_alloc( sz );
1488 if( !p )
1490 msi_free( row );
1491 return ERROR_NOT_ENOUGH_MEMORY;
1494 sz = (*row_count + 1) * sizeof (BOOL);
1495 if( *data_persist_ptr )
1496 b = msi_realloc( *data_persist_ptr, sz );
1497 else
1498 b = msi_alloc( sz );
1499 if( !b )
1501 msi_free( row );
1502 msi_free( p );
1503 return ERROR_NOT_ENOUGH_MEMORY;
1506 *data_ptr = p;
1507 (*data_ptr)[*row_count] = row;
1509 *data_persist_ptr = b;
1510 (*data_persist_ptr)[*row_count] = !temporary;
1512 (*row_count)++;
1514 return ERROR_SUCCESS;
1517 static UINT TABLE_execute( struct tagMSIVIEW *view, MSIRECORD *record )
1519 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1521 TRACE("%p %p\n", tv, record);
1523 TRACE("There are %d columns\n", tv->num_cols );
1525 return ERROR_SUCCESS;
1528 static UINT TABLE_close( struct tagMSIVIEW *view )
1530 TRACE("%p\n", view );
1532 return ERROR_SUCCESS;
1535 static UINT TABLE_get_dimensions( struct tagMSIVIEW *view, UINT *rows, UINT *cols)
1537 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1539 TRACE("%p %p %p\n", view, rows, cols );
1541 if( cols )
1542 *cols = tv->num_cols;
1543 if( rows )
1545 if( !tv->table )
1546 return ERROR_INVALID_PARAMETER;
1547 *rows = tv->table->row_count;
1550 return ERROR_SUCCESS;
1553 static UINT TABLE_get_column_info( struct tagMSIVIEW *view,
1554 UINT n, LPWSTR *name, UINT *type, BOOL *temporary,
1555 LPWSTR *table_name )
1557 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1559 TRACE("%p %d %p %p\n", tv, n, name, type );
1561 if( ( n == 0 ) || ( n > tv->num_cols ) )
1562 return ERROR_INVALID_PARAMETER;
1564 if( name )
1566 *name = strdupW( tv->columns[n-1].colname );
1567 if( !*name )
1568 return ERROR_FUNCTION_FAILED;
1571 if( table_name )
1573 *table_name = strdupW( tv->columns[n-1].tablename );
1574 if( !*table_name )
1575 return ERROR_FUNCTION_FAILED;
1578 if( type )
1579 *type = tv->columns[n-1].type;
1581 if( temporary )
1582 *temporary = tv->columns[n-1].temporary;
1584 return ERROR_SUCCESS;
1587 static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row );
1589 static UINT table_validate_new( MSITABLEVIEW *tv, MSIRECORD *rec )
1591 UINT r, row, i;
1593 /* check there's no null values where they're not allowed */
1594 for( i = 0; i < tv->num_cols; i++ )
1596 if ( tv->columns[i].type & MSITYPE_NULLABLE )
1597 continue;
1599 if ( MSITYPE_IS_BINARY(tv->columns[i].type) )
1600 TRACE("skipping binary column\n");
1601 else if ( tv->columns[i].type & MSITYPE_STRING )
1603 LPCWSTR str;
1605 str = MSI_RecordGetString( rec, i+1 );
1606 if (str == NULL || str[0] == 0)
1607 return ERROR_INVALID_DATA;
1609 else
1611 UINT n;
1613 n = MSI_RecordGetInteger( rec, i+1 );
1614 if (n == MSI_NULL_INTEGER)
1615 return ERROR_INVALID_DATA;
1619 /* check there's no duplicate keys */
1620 r = msi_table_find_row( tv, rec, &row );
1621 if (r == ERROR_SUCCESS)
1622 return ERROR_FUNCTION_FAILED;
1624 return ERROR_SUCCESS;
1627 static int compare_record( MSITABLEVIEW *tv, UINT row, MSIRECORD *rec )
1629 UINT r, i, ivalue, x;
1631 for (i = 0; i < tv->num_cols; i++ )
1633 if (!(tv->columns[i].type & MSITYPE_KEY)) continue;
1635 r = get_table_value_from_record( tv, rec, i + 1, &ivalue );
1636 if (r != ERROR_SUCCESS)
1637 return 1;
1639 r = TABLE_fetch_int( &tv->view, row, i + 1, &x );
1640 if (r != ERROR_SUCCESS)
1642 WARN("TABLE_fetch_int should not fail here %u\n", r);
1643 return -1;
1645 if (ivalue > x)
1647 return 1;
1649 else if (ivalue == x)
1651 if (i < tv->num_cols - 1) continue;
1652 return 0;
1654 else
1655 return -1;
1657 return 1;
1660 static int find_insert_index( MSITABLEVIEW *tv, MSIRECORD *rec )
1662 int idx, c, low = 0, high = tv->table->row_count - 1;
1664 TRACE("%p %p\n", tv, rec);
1666 while (low <= high)
1668 idx = (low + high) / 2;
1669 c = compare_record( tv, idx, rec );
1671 if (c < 0)
1672 high = idx - 1;
1673 else if (c > 0)
1674 low = idx + 1;
1675 else
1677 TRACE("found %u\n", idx);
1678 return idx;
1681 TRACE("found %u\n", high + 1);
1682 return high + 1;
1685 static UINT TABLE_insert_row( struct tagMSIVIEW *view, MSIRECORD *rec, UINT row, BOOL temporary )
1687 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1688 UINT i, r;
1690 TRACE("%p %p %s\n", tv, rec, temporary ? "TRUE" : "FALSE" );
1692 /* check that the key is unique - can we find a matching row? */
1693 r = table_validate_new( tv, rec );
1694 if( r != ERROR_SUCCESS )
1695 return ERROR_FUNCTION_FAILED;
1697 if (row == -1)
1698 row = find_insert_index( tv, rec );
1700 r = table_create_new_row( view, &row, temporary );
1701 TRACE("insert_row returned %08x\n", r);
1702 if( r != ERROR_SUCCESS )
1703 return r;
1705 /* shift the rows to make room for the new row */
1706 for (i = tv->table->row_count - 1; i > row; i--)
1708 memmove(&(tv->table->data[i][0]),
1709 &(tv->table->data[i - 1][0]), tv->row_size);
1710 tv->table->data_persistent[i] = tv->table->data_persistent[i - 1];
1713 /* Re-set the persistence flag */
1714 tv->table->data_persistent[row] = !temporary;
1715 return TABLE_set_row( view, row, rec, (1<<tv->num_cols) - 1 );
1718 static UINT TABLE_delete_row( struct tagMSIVIEW *view, UINT row )
1720 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1721 UINT r, num_rows, num_cols, i;
1723 TRACE("%p %d\n", tv, row);
1725 if ( !tv->table )
1726 return ERROR_INVALID_PARAMETER;
1728 r = TABLE_get_dimensions( view, &num_rows, &num_cols );
1729 if ( r != ERROR_SUCCESS )
1730 return r;
1732 if ( row >= num_rows )
1733 return ERROR_FUNCTION_FAILED;
1735 num_rows = tv->table->row_count;
1736 tv->table->row_count--;
1738 /* reset the hash tables */
1739 for (i = 0; i < tv->num_cols; i++)
1741 msi_free( tv->columns[i].hash_table );
1742 tv->columns[i].hash_table = NULL;
1745 for (i = row + 1; i < num_rows; i++)
1747 memcpy(tv->table->data[i - 1], tv->table->data[i], tv->row_size);
1748 tv->table->data_persistent[i - 1] = tv->table->data_persistent[i];
1751 msi_free(tv->table->data[num_rows - 1]);
1753 return ERROR_SUCCESS;
1756 static UINT msi_table_update(struct tagMSIVIEW *view, MSIRECORD *rec, UINT row)
1758 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1759 UINT r, new_row;
1761 /* FIXME: MsiViewFetch should set rec index 0 to some ID that
1762 * sets the fetched record apart from other records
1765 if (!tv->table)
1766 return ERROR_INVALID_PARAMETER;
1768 r = msi_table_find_row(tv, rec, &new_row);
1769 if (r != ERROR_SUCCESS)
1771 ERR("can't find row to modify\n");
1772 return ERROR_FUNCTION_FAILED;
1775 /* the row cannot be changed */
1776 if (row != new_row + 1)
1777 return ERROR_FUNCTION_FAILED;
1779 if(tv->order)
1780 new_row = tv->order->reorder[new_row];
1782 return TABLE_set_row(view, new_row, rec, (1 << tv->num_cols) - 1);
1785 static UINT msi_table_assign(struct tagMSIVIEW *view, MSIRECORD *rec)
1787 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1788 UINT r, row;
1790 if (!tv->table)
1791 return ERROR_INVALID_PARAMETER;
1793 r = msi_table_find_row(tv, rec, &row);
1794 if (r == ERROR_SUCCESS)
1795 return TABLE_set_row(view, row, rec, (1 << tv->num_cols) - 1);
1796 else
1797 return TABLE_insert_row( view, rec, -1, FALSE );
1800 static UINT modify_delete_row( struct tagMSIVIEW *view, MSIRECORD *rec )
1802 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1803 UINT row, r;
1805 r = msi_table_find_row(tv, rec, &row);
1806 if (r != ERROR_SUCCESS)
1807 return r;
1809 return TABLE_delete_row(view, row);
1812 static UINT msi_refresh_record( struct tagMSIVIEW *view, MSIRECORD *rec, UINT row )
1814 MSIRECORD *curr;
1815 UINT r, i, count;
1817 r = TABLE_get_row(view, row - 1, &curr);
1818 if (r != ERROR_SUCCESS)
1819 return r;
1821 /* Close the original record */
1822 MSI_CloseRecord(&rec->hdr);
1824 count = MSI_RecordGetFieldCount(rec);
1825 for (i = 0; i < count; i++)
1826 MSI_RecordCopyField(curr, i + 1, rec, i + 1);
1828 msiobj_release(&curr->hdr);
1829 return ERROR_SUCCESS;
1832 static UINT TABLE_modify( struct tagMSIVIEW *view, MSIMODIFY eModifyMode,
1833 MSIRECORD *rec, UINT row)
1835 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1836 UINT r;
1838 TRACE("%p %d %p\n", view, eModifyMode, rec );
1840 switch (eModifyMode)
1842 case MSIMODIFY_DELETE:
1843 r = modify_delete_row( view, rec );
1844 break;
1845 case MSIMODIFY_VALIDATE_NEW:
1846 r = table_validate_new( tv, rec );
1847 break;
1849 case MSIMODIFY_INSERT:
1850 r = table_validate_new( tv, rec );
1851 if (r != ERROR_SUCCESS)
1852 break;
1853 r = TABLE_insert_row( view, rec, -1, FALSE );
1854 break;
1856 case MSIMODIFY_INSERT_TEMPORARY:
1857 r = table_validate_new( tv, rec );
1858 if (r != ERROR_SUCCESS)
1859 break;
1860 r = TABLE_insert_row( view, rec, -1, TRUE );
1861 break;
1863 case MSIMODIFY_REFRESH:
1864 r = msi_refresh_record( view, rec, row );
1865 break;
1867 case MSIMODIFY_UPDATE:
1868 r = msi_table_update( view, rec, row );
1869 break;
1871 case MSIMODIFY_ASSIGN:
1872 r = msi_table_assign( view, rec );
1873 break;
1875 case MSIMODIFY_REPLACE:
1876 case MSIMODIFY_MERGE:
1877 case MSIMODIFY_VALIDATE:
1878 case MSIMODIFY_VALIDATE_FIELD:
1879 case MSIMODIFY_VALIDATE_DELETE:
1880 FIXME("%p %d %p - mode not implemented\n", view, eModifyMode, rec );
1881 r = ERROR_CALL_NOT_IMPLEMENTED;
1882 break;
1884 default:
1885 r = ERROR_INVALID_DATA;
1888 return r;
1891 static UINT TABLE_delete( struct tagMSIVIEW *view )
1893 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1895 TRACE("%p\n", view );
1897 tv->table = NULL;
1898 tv->columns = NULL;
1900 if (tv->order)
1902 msi_free( tv->order->reorder );
1903 msi_free( tv->order );
1904 tv->order = NULL;
1907 msi_free( tv );
1909 return ERROR_SUCCESS;
1912 static UINT TABLE_find_matching_rows( struct tagMSIVIEW *view, UINT col,
1913 UINT val, UINT *row, MSIITERHANDLE *handle )
1915 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1916 const MSICOLUMNHASHENTRY *entry;
1918 TRACE("%p, %d, %u, %p\n", view, col, val, *handle);
1920 if( !tv->table )
1921 return ERROR_INVALID_PARAMETER;
1923 if( (col==0) || (col > tv->num_cols) )
1924 return ERROR_INVALID_PARAMETER;
1926 if( !tv->columns[col-1].hash_table )
1928 UINT i;
1929 UINT num_rows = tv->table->row_count;
1930 MSICOLUMNHASHENTRY **hash_table;
1931 MSICOLUMNHASHENTRY *new_entry;
1933 if( tv->columns[col-1].offset >= tv->row_size )
1935 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1936 ERR("%p %p\n", tv, tv->columns );
1937 return ERROR_FUNCTION_FAILED;
1940 /* allocate contiguous memory for the table and its entries so we
1941 * don't have to do an expensive cleanup */
1942 hash_table = msi_alloc(MSITABLE_HASH_TABLE_SIZE * sizeof(MSICOLUMNHASHENTRY*) +
1943 num_rows * sizeof(MSICOLUMNHASHENTRY));
1944 if (!hash_table)
1945 return ERROR_OUTOFMEMORY;
1947 memset(hash_table, 0, MSITABLE_HASH_TABLE_SIZE * sizeof(MSICOLUMNHASHENTRY*));
1948 tv->columns[col-1].hash_table = hash_table;
1950 new_entry = (MSICOLUMNHASHENTRY *)(hash_table + MSITABLE_HASH_TABLE_SIZE);
1952 for (i = 0; i < num_rows; i++, new_entry++)
1954 UINT row_value;
1956 if (view->ops->fetch_int( view, i, col, &row_value ) != ERROR_SUCCESS)
1957 continue;
1959 new_entry->next = NULL;
1960 new_entry->value = row_value;
1961 new_entry->row = i;
1962 if (hash_table[row_value % MSITABLE_HASH_TABLE_SIZE])
1964 MSICOLUMNHASHENTRY *prev_entry = hash_table[row_value % MSITABLE_HASH_TABLE_SIZE];
1965 while (prev_entry->next)
1966 prev_entry = prev_entry->next;
1967 prev_entry->next = new_entry;
1969 else
1970 hash_table[row_value % MSITABLE_HASH_TABLE_SIZE] = new_entry;
1974 if( !*handle )
1975 entry = tv->columns[col-1].hash_table[val % MSITABLE_HASH_TABLE_SIZE];
1976 else
1977 entry = (*handle)->next;
1979 while (entry && entry->value != val)
1980 entry = entry->next;
1982 *handle = entry;
1983 if (!entry)
1984 return ERROR_NO_MORE_ITEMS;
1986 *row = entry->row;
1988 return ERROR_SUCCESS;
1991 static UINT TABLE_add_ref(struct tagMSIVIEW *view)
1993 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1994 UINT i;
1996 TRACE("%p %d\n", view, tv->table->ref_count);
1998 for (i = 0; i < tv->table->col_count; i++)
2000 if (tv->table->colinfo[i].type & MSITYPE_TEMPORARY)
2001 InterlockedIncrement(&tv->table->colinfo[i].ref_count);
2004 return InterlockedIncrement(&tv->table->ref_count);
2007 static UINT TABLE_remove_column(struct tagMSIVIEW *view, LPCWSTR table, UINT number)
2009 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2010 MSIRECORD *rec = NULL;
2011 MSIVIEW *columns = NULL;
2012 UINT row, r;
2014 rec = MSI_CreateRecord(2);
2015 if (!rec)
2016 return ERROR_OUTOFMEMORY;
2018 MSI_RecordSetStringW(rec, 1, table);
2019 MSI_RecordSetInteger(rec, 2, number);
2021 r = TABLE_CreateView(tv->db, szColumns, &columns);
2022 if (r != ERROR_SUCCESS)
2023 return r;
2025 r = msi_table_find_row((MSITABLEVIEW *)columns, rec, &row);
2026 if (r != ERROR_SUCCESS)
2027 goto done;
2029 r = TABLE_delete_row(columns, row);
2030 if (r != ERROR_SUCCESS)
2031 goto done;
2033 msi_update_table_columns(tv->db, table);
2035 done:
2036 msiobj_release(&rec->hdr);
2037 columns->ops->delete(columns);
2038 return r;
2041 static UINT TABLE_release(struct tagMSIVIEW *view)
2043 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2044 INT ref = tv->table->ref_count;
2045 UINT i, r;
2047 TRACE("%p %d\n", view, ref);
2049 for (i = 0; i < tv->table->col_count; i++)
2051 if (tv->table->colinfo[i].type & MSITYPE_TEMPORARY)
2053 ref = InterlockedDecrement(&tv->table->colinfo[i].ref_count);
2054 if (ref == 0)
2056 r = TABLE_remove_column(view, tv->table->colinfo[i].tablename,
2057 tv->table->colinfo[i].number);
2058 if (r != ERROR_SUCCESS)
2059 break;
2064 ref = InterlockedDecrement(&tv->table->ref_count);
2065 if (ref == 0)
2067 if (!tv->table->row_count)
2069 list_remove(&tv->table->entry);
2070 free_table(tv->table);
2071 TABLE_delete(view);
2075 return ref;
2078 static UINT TABLE_add_column(struct tagMSIVIEW *view, LPCWSTR table, UINT number,
2079 LPCWSTR column, UINT type, BOOL hold)
2081 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2082 MSITABLE *msitable;
2083 MSIRECORD *rec;
2084 UINT r, i;
2086 rec = MSI_CreateRecord(4);
2087 if (!rec)
2088 return ERROR_OUTOFMEMORY;
2090 MSI_RecordSetStringW(rec, 1, table);
2091 MSI_RecordSetInteger(rec, 2, number);
2092 MSI_RecordSetStringW(rec, 3, column);
2093 MSI_RecordSetInteger(rec, 4, type);
2095 r = TABLE_insert_row(&tv->view, rec, -1, FALSE);
2096 if (r != ERROR_SUCCESS)
2097 goto done;
2099 msi_update_table_columns(tv->db, table);
2101 if (!hold)
2102 goto done;
2104 msitable = find_cached_table(tv->db, table);
2105 for (i = 0; i < msitable->col_count; i++)
2107 if (!strcmpW( msitable->colinfo[i].colname, column ))
2109 InterlockedIncrement(&msitable->colinfo[i].ref_count);
2110 break;
2114 done:
2115 msiobj_release(&rec->hdr);
2116 return r;
2119 static UINT order_add_column(struct tagMSIVIEW *view, MSIORDERINFO *order, LPCWSTR name)
2121 UINT n, r, count;
2122 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2124 r = TABLE_get_dimensions(view, NULL, &count);
2125 if (r != ERROR_SUCCESS)
2126 return r;
2128 if (order->num_cols >= count)
2129 return ERROR_FUNCTION_FAILED;
2131 r = VIEW_find_column(view, name, tv->name, &n);
2132 if (r != ERROR_SUCCESS)
2133 return r;
2135 order->cols[order->num_cols] = n;
2136 TRACE("Ordering by column %s (%d)\n", debugstr_w(name), n);
2138 order->num_cols++;
2140 return ERROR_SUCCESS;
2143 static UINT order_compare(struct tagMSIVIEW *view, MSIORDERINFO *order,
2144 UINT a, UINT b, UINT *swap)
2146 UINT r, i, a_val = 0, b_val = 0;
2148 *swap = 0;
2149 for (i = 0; i < order->num_cols; i++)
2151 r = TABLE_fetch_int(view, a, order->cols[i], &a_val);
2152 if (r != ERROR_SUCCESS)
2153 return r;
2155 r = TABLE_fetch_int(view, b, order->cols[i], &b_val);
2156 if (r != ERROR_SUCCESS)
2157 return r;
2159 if (a_val != b_val)
2161 if (a_val > b_val)
2162 *swap = 1;
2163 break;
2167 return ERROR_SUCCESS;
2170 static UINT order_mergesort(struct tagMSIVIEW *view, MSIORDERINFO *order,
2171 UINT left, UINT right)
2173 UINT r, i, j, temp;
2174 UINT swap = 0, center = (left + right) / 2;
2175 UINT *array = order->reorder;
2177 if (left == right)
2178 return ERROR_SUCCESS;
2180 /* sort the left half */
2181 r = order_mergesort(view, order, left, center);
2182 if (r != ERROR_SUCCESS)
2183 return r;
2185 /* sort the right half */
2186 r = order_mergesort(view, order, center + 1, right);
2187 if (r != ERROR_SUCCESS)
2188 return r;
2190 for (i = left, j = center + 1; (i <= center) && (j <= right); i++)
2192 r = order_compare(view, order, array[i], array[j], &swap);
2193 if (r != ERROR_SUCCESS)
2194 return r;
2196 if (swap)
2198 temp = array[j];
2199 memmove(&array[i + 1], &array[i], (j - i) * sizeof(UINT));
2200 array[i] = temp;
2201 j++;
2202 center++;
2206 return ERROR_SUCCESS;
2209 static UINT order_verify(struct tagMSIVIEW *view, MSIORDERINFO *order, UINT num_rows)
2211 UINT i, swap, r;
2213 for (i = 1; i < num_rows; i++)
2215 r = order_compare(view, order, order->reorder[i - 1],
2216 order->reorder[i], &swap);
2217 if (r != ERROR_SUCCESS)
2218 return r;
2220 if (!swap)
2221 continue;
2223 ERR("Bad order! %d\n", i);
2224 return ERROR_FUNCTION_FAILED;
2227 return ERROR_SUCCESS;
2230 static UINT TABLE_sort(struct tagMSIVIEW *view, column_info *columns)
2232 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
2233 MSIORDERINFO *order;
2234 column_info *ptr;
2235 UINT r, i;
2236 UINT rows, cols;
2238 TRACE("sorting table %s\n", debugstr_w(tv->name));
2240 r = TABLE_get_dimensions(view, &rows, &cols);
2241 if (r != ERROR_SUCCESS)
2242 return r;
2244 if (rows == 0)
2245 return ERROR_SUCCESS;
2247 order = msi_alloc_zero(sizeof(MSIORDERINFO) + sizeof(UINT) * cols);
2248 if (!order)
2249 return ERROR_OUTOFMEMORY;
2251 for (ptr = columns; ptr; ptr = ptr->next)
2252 order_add_column(view, order, ptr->column);
2254 order->reorder = msi_alloc(rows * sizeof(UINT));
2255 if (!order->reorder)
2256 return ERROR_OUTOFMEMORY;
2258 for (i = 0; i < rows; i++)
2259 order->reorder[i] = i;
2261 r = order_mergesort(view, order, 0, rows - 1);
2262 if (r != ERROR_SUCCESS)
2263 return r;
2265 r = order_verify(view, order, rows);
2266 if (r != ERROR_SUCCESS)
2267 return r;
2269 tv->order = order;
2271 return ERROR_SUCCESS;
2274 static UINT TABLE_drop(struct tagMSIVIEW *view)
2276 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2277 MSIVIEW *tables = NULL;
2278 MSIRECORD *rec = NULL;
2279 UINT r, row;
2280 INT i;
2282 TRACE("dropping table %s\n", debugstr_w(tv->name));
2284 for (i = tv->table->col_count - 1; i >= 0; i--)
2286 r = TABLE_remove_column(view, tv->table->colinfo[i].tablename,
2287 tv->table->colinfo[i].number);
2288 if (r != ERROR_SUCCESS)
2289 return r;
2292 rec = MSI_CreateRecord(1);
2293 if (!rec)
2294 return ERROR_OUTOFMEMORY;
2296 MSI_RecordSetStringW(rec, 1, tv->name);
2298 r = TABLE_CreateView(tv->db, szTables, &tables);
2299 if (r != ERROR_SUCCESS)
2300 return r;
2302 r = msi_table_find_row((MSITABLEVIEW *)tables, rec, &row);
2303 if (r != ERROR_SUCCESS)
2304 goto done;
2306 r = TABLE_delete_row(tables, row);
2307 if (r != ERROR_SUCCESS)
2308 goto done;
2310 list_remove(&tv->table->entry);
2311 free_table(tv->table);
2313 done:
2314 msiobj_release(&rec->hdr);
2315 tables->ops->delete(tables);
2317 return r;
2320 static const MSIVIEWOPS table_ops =
2322 TABLE_fetch_int,
2323 TABLE_fetch_stream,
2324 TABLE_get_row,
2325 TABLE_set_row,
2326 TABLE_insert_row,
2327 TABLE_delete_row,
2328 TABLE_execute,
2329 TABLE_close,
2330 TABLE_get_dimensions,
2331 TABLE_get_column_info,
2332 TABLE_modify,
2333 TABLE_delete,
2334 TABLE_find_matching_rows,
2335 TABLE_add_ref,
2336 TABLE_release,
2337 TABLE_add_column,
2338 TABLE_remove_column,
2339 TABLE_sort,
2340 TABLE_drop,
2343 UINT TABLE_CreateView( MSIDATABASE *db, LPCWSTR name, MSIVIEW **view )
2345 MSITABLEVIEW *tv ;
2346 UINT r, sz;
2348 TRACE("%p %s %p\n", db, debugstr_w(name), view );
2350 if ( !strcmpW( name, szStreams ) )
2351 return STREAMS_CreateView( db, view );
2352 else if ( !strcmpW( name, szStorages ) )
2353 return STORAGES_CreateView( db, view );
2355 sz = sizeof *tv + lstrlenW(name)*sizeof name[0] ;
2356 tv = msi_alloc_zero( sz );
2357 if( !tv )
2358 return ERROR_FUNCTION_FAILED;
2360 r = get_table( db, name, &tv->table );
2361 if( r != ERROR_SUCCESS )
2363 msi_free( tv );
2364 WARN("table not found\n");
2365 return r;
2368 TRACE("table %p found with %d columns\n", tv->table, tv->table->col_count);
2370 /* fill the structure */
2371 tv->view.ops = &table_ops;
2372 tv->db = db;
2373 tv->columns = tv->table->colinfo;
2374 tv->num_cols = tv->table->col_count;
2375 tv->row_size = msi_table_get_row_size( db, tv->table->colinfo, tv->table->col_count, LONG_STR_BYTES );
2377 TRACE("%s one row is %d bytes\n", debugstr_w(name), tv->row_size );
2379 *view = (MSIVIEW*) tv;
2380 lstrcpyW( tv->name, name );
2382 return ERROR_SUCCESS;
2385 UINT MSI_CommitTables( MSIDATABASE *db )
2387 UINT r, bytes_per_strref;
2388 HRESULT hr;
2389 MSITABLE *table = NULL;
2391 TRACE("%p\n",db);
2393 r = msi_save_string_table( db->strings, db->storage, &bytes_per_strref );
2394 if( r != ERROR_SUCCESS )
2396 WARN("failed to save string table r=%08x\n",r);
2397 return r;
2400 LIST_FOR_EACH_ENTRY( table, &db->tables, MSITABLE, entry )
2402 r = save_table( db, table, bytes_per_strref );
2403 if( r != ERROR_SUCCESS )
2405 WARN("failed to save table %s (r=%08x)\n",
2406 debugstr_w(table->name), r);
2407 return r;
2411 /* force everything to reload next time */
2412 free_cached_tables( db );
2414 hr = IStorage_Commit( db->storage, 0 );
2415 if (FAILED( hr ))
2417 WARN("failed to commit changes 0x%08x\n", hr);
2418 r = ERROR_FUNCTION_FAILED;
2420 return r;
2423 MSICONDITION MSI_DatabaseIsTablePersistent( MSIDATABASE *db, LPCWSTR table )
2425 MSITABLE *t;
2426 UINT r;
2428 TRACE("%p %s\n", db, debugstr_w(table));
2430 if (!table)
2431 return MSICONDITION_ERROR;
2433 r = get_table( db, table, &t );
2434 if (r != ERROR_SUCCESS)
2435 return MSICONDITION_NONE;
2437 return t->persistent;
2440 static UINT read_raw_int(const BYTE *data, UINT col, UINT bytes)
2442 UINT ret = 0, i;
2444 for (i = 0; i < bytes; i++)
2445 ret += (data[col + i] << i * 8);
2447 return ret;
2450 static UINT msi_record_encoded_stream_name( const MSITABLEVIEW *tv, MSIRECORD *rec, LPWSTR *pstname )
2452 LPWSTR stname = NULL, sval, p;
2453 DWORD len;
2454 UINT i, r;
2456 TRACE("%p %p\n", tv, rec);
2458 len = lstrlenW( tv->name ) + 1;
2459 stname = msi_alloc( len*sizeof(WCHAR) );
2460 if ( !stname )
2462 r = ERROR_OUTOFMEMORY;
2463 goto err;
2466 lstrcpyW( stname, tv->name );
2468 for ( i = 0; i < tv->num_cols; i++ )
2470 if ( tv->columns[i].type & MSITYPE_KEY )
2472 sval = msi_dup_record_field( rec, i + 1 );
2473 if ( !sval )
2475 r = ERROR_OUTOFMEMORY;
2476 goto err;
2479 len += lstrlenW( szDot ) + lstrlenW ( sval );
2480 p = msi_realloc ( stname, len*sizeof(WCHAR) );
2481 if ( !p )
2483 r = ERROR_OUTOFMEMORY;
2484 goto err;
2486 stname = p;
2488 lstrcatW( stname, szDot );
2489 lstrcatW( stname, sval );
2491 msi_free( sval );
2493 else
2494 continue;
2497 *pstname = encode_streamname( FALSE, stname );
2498 msi_free( stname );
2500 return ERROR_SUCCESS;
2502 err:
2503 msi_free ( stname );
2504 *pstname = NULL;
2505 return r;
2508 static MSIRECORD *msi_get_transform_record( const MSITABLEVIEW *tv, const string_table *st,
2509 IStorage *stg,
2510 const BYTE *rawdata, UINT bytes_per_strref )
2512 UINT i, val, ofs = 0;
2513 USHORT mask;
2514 MSICOLUMNINFO *columns = tv->columns;
2515 MSIRECORD *rec;
2517 mask = rawdata[0] | (rawdata[1] << 8);
2518 rawdata += 2;
2520 rec = MSI_CreateRecord( tv->num_cols );
2521 if( !rec )
2522 return rec;
2524 TRACE("row ->\n");
2525 for( i=0; i<tv->num_cols; i++ )
2527 if ( (mask&1) && (i>=(mask>>8)) )
2528 break;
2529 /* all keys must be present */
2530 if ( (~mask&1) && (~columns[i].type & MSITYPE_KEY) && ((1<<i) & ~mask) )
2531 continue;
2533 if( MSITYPE_IS_BINARY(tv->columns[i].type) )
2535 LPWSTR encname;
2536 IStream *stm = NULL;
2537 UINT r;
2539 ofs += bytes_per_column( tv->db, &columns[i], bytes_per_strref );
2541 r = msi_record_encoded_stream_name( tv, rec, &encname );
2542 if ( r != ERROR_SUCCESS )
2543 return NULL;
2545 r = IStorage_OpenStream( stg, encname, NULL,
2546 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &stm );
2547 msi_free( encname );
2548 if ( r != ERROR_SUCCESS )
2549 return NULL;
2551 MSI_RecordSetStream( rec, i+1, stm );
2552 TRACE(" field %d [%s]\n", i+1, debugstr_w(encname));
2554 else if( columns[i].type & MSITYPE_STRING )
2556 LPCWSTR sval;
2558 val = read_raw_int(rawdata, ofs, bytes_per_strref);
2559 sval = msi_string_lookup_id( st, val );
2560 MSI_RecordSetStringW( rec, i+1, sval );
2561 TRACE(" field %d [%s]\n", i+1, debugstr_w(sval));
2562 ofs += bytes_per_strref;
2564 else
2566 UINT n = bytes_per_column( tv->db, &columns[i], bytes_per_strref );
2567 switch( n )
2569 case 2:
2570 val = read_raw_int(rawdata, ofs, n);
2571 if (val)
2572 MSI_RecordSetInteger( rec, i+1, val-0x8000 );
2573 TRACE(" field %d [0x%04x]\n", i+1, val );
2574 break;
2575 case 4:
2576 val = read_raw_int(rawdata, ofs, n);
2577 if (val)
2578 MSI_RecordSetInteger( rec, i+1, val^0x80000000 );
2579 TRACE(" field %d [0x%08x]\n", i+1, val );
2580 break;
2581 default:
2582 ERR("oops - unknown column width %d\n", n);
2583 break;
2585 ofs += n;
2588 return rec;
2591 static void dump_record( MSIRECORD *rec )
2593 UINT i, n;
2595 n = MSI_RecordGetFieldCount( rec );
2596 for( i=1; i<=n; i++ )
2598 LPCWSTR sval = MSI_RecordGetString( rec, i );
2600 if( MSI_RecordIsNull( rec, i ) )
2601 TRACE("row -> []\n");
2602 else if( (sval = MSI_RecordGetString( rec, i )) )
2603 TRACE("row -> [%s]\n", debugstr_w(sval));
2604 else
2605 TRACE("row -> [0x%08x]\n", MSI_RecordGetInteger( rec, i ) );
2609 static void dump_table( const string_table *st, const USHORT *rawdata, UINT rawsize )
2611 LPCWSTR sval;
2612 UINT i;
2614 for( i=0; i<(rawsize/2); i++ )
2616 sval = msi_string_lookup_id( st, rawdata[i] );
2617 MESSAGE(" %04x %s\n", rawdata[i], debugstr_w(sval) );
2621 static UINT* msi_record_to_row( const MSITABLEVIEW *tv, MSIRECORD *rec )
2623 LPCWSTR str;
2624 UINT i, r, *data;
2626 data = msi_alloc( tv->num_cols *sizeof (UINT) );
2627 for( i=0; i<tv->num_cols; i++ )
2629 data[i] = 0;
2631 if ( ~tv->columns[i].type & MSITYPE_KEY )
2632 continue;
2634 /* turn the transform column value into a row value */
2635 if ( ( tv->columns[i].type & MSITYPE_STRING ) &&
2636 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2638 str = MSI_RecordGetString( rec, i+1 );
2639 if (str)
2641 r = msi_string2idW( tv->db->strings, str, &data[i] );
2643 /* if there's no matching string in the string table,
2644 these keys can't match any record, so fail now. */
2645 if (r != ERROR_SUCCESS)
2647 msi_free( data );
2648 return NULL;
2651 else data[i] = 0;
2653 else
2655 data[i] = MSI_RecordGetInteger( rec, i+1 );
2657 if (data[i] == MSI_NULL_INTEGER)
2658 data[i] = 0;
2659 else if ((tv->columns[i].type&0xff) == 2)
2660 data[i] += 0x8000;
2661 else
2662 data[i] += 0x80000000;
2665 return data;
2668 static UINT msi_row_matches( MSITABLEVIEW *tv, UINT row, const UINT *data )
2670 UINT i, r, x, ret = ERROR_FUNCTION_FAILED;
2672 for( i=0; i<tv->num_cols; i++ )
2674 if ( ~tv->columns[i].type & MSITYPE_KEY )
2675 continue;
2677 /* turn the transform column value into a row value */
2678 r = TABLE_fetch_int( &tv->view, row, i+1, &x );
2679 if ( r != ERROR_SUCCESS )
2681 ERR("TABLE_fetch_int shouldn't fail here\n");
2682 break;
2685 /* if this key matches, move to the next column */
2686 if ( x != data[i] )
2688 ret = ERROR_FUNCTION_FAILED;
2689 break;
2692 ret = ERROR_SUCCESS;
2695 return ret;
2698 static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row )
2700 UINT i, r = ERROR_FUNCTION_FAILED, *data;
2702 data = msi_record_to_row( tv, rec );
2703 if( !data )
2704 return r;
2705 for( i = 0; i < tv->table->row_count; i++ )
2707 r = msi_row_matches( tv, i, data );
2708 if( r == ERROR_SUCCESS )
2710 *row = i;
2711 break;
2714 msi_free( data );
2715 return r;
2718 typedef struct
2720 struct list entry;
2721 LPWSTR name;
2722 } TRANSFORMDATA;
2724 static UINT msi_table_load_transform( MSIDATABASE *db, IStorage *stg,
2725 string_table *st, TRANSFORMDATA *transform,
2726 UINT bytes_per_strref )
2728 UINT rawsize = 0;
2729 BYTE *rawdata = NULL;
2730 MSITABLEVIEW *tv = NULL;
2731 UINT r, n, sz, i, mask;
2732 MSIRECORD *rec = NULL;
2733 UINT colcol = 0;
2734 WCHAR coltable[32];
2735 LPWSTR name;
2737 if (!transform)
2738 return ERROR_SUCCESS;
2740 name = transform->name;
2742 coltable[0] = 0;
2743 TRACE("%p %p %p %s\n", db, stg, st, debugstr_w(name) );
2745 /* read the transform data */
2746 read_stream_data( stg, name, TRUE, &rawdata, &rawsize );
2747 if ( !rawdata )
2749 TRACE("table %s empty\n", debugstr_w(name) );
2750 return ERROR_INVALID_TABLE;
2753 /* create a table view */
2754 r = TABLE_CreateView( db, name, (MSIVIEW**) &tv );
2755 if( r != ERROR_SUCCESS )
2756 goto err;
2758 r = tv->view.ops->execute( &tv->view, NULL );
2759 if( r != ERROR_SUCCESS )
2760 goto err;
2762 TRACE("name = %s columns = %u row_size = %u raw size = %u\n",
2763 debugstr_w(name), tv->num_cols, tv->row_size, rawsize );
2765 /* interpret the data */
2766 r = ERROR_SUCCESS;
2767 for( n=0; n < rawsize; )
2769 mask = rawdata[n] | (rawdata[n+1] << 8);
2771 if (mask&1)
2774 * if the low bit is set, columns are continuous and
2775 * the number of columns is specified in the high byte
2777 sz = 2;
2778 for( i=0; i<tv->num_cols; i++ )
2780 if( (tv->columns[i].type & MSITYPE_STRING) &&
2781 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2782 sz += bytes_per_strref;
2783 else
2784 sz += bytes_per_column( tv->db, &tv->columns[i], bytes_per_strref );
2787 else
2790 * If the low bit is not set, mask is a bitmask.
2791 * Excepting for key fields, which are always present,
2792 * each bit indicates that a field is present in the transform record.
2794 * mask == 0 is a special case ... only the keys will be present
2795 * and it means that this row should be deleted.
2797 sz = 2;
2798 for( i=0; i<tv->num_cols; i++ )
2800 if( (tv->columns[i].type & MSITYPE_KEY) || ((1<<i)&mask))
2802 if( (tv->columns[i].type & MSITYPE_STRING) &&
2803 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2804 sz += bytes_per_strref;
2805 else
2806 sz += bytes_per_column( tv->db, &tv->columns[i], bytes_per_strref );
2811 /* check we didn't run of the end of the table */
2812 if ( (n+sz) > rawsize )
2814 ERR("borked.\n");
2815 dump_table( st, (USHORT *)rawdata, rawsize );
2816 break;
2819 rec = msi_get_transform_record( tv, st, stg, &rawdata[n], bytes_per_strref );
2820 if (rec)
2822 WCHAR table[32];
2823 DWORD sz = 32;
2824 UINT number = MSI_NULL_INTEGER;
2825 UINT row = 0;
2827 if (!strcmpW( name, szColumns ))
2829 MSI_RecordGetStringW( rec, 1, table, &sz );
2830 number = MSI_RecordGetInteger( rec, 2 );
2833 * Native msi seems writes nul into the Number (2nd) column of
2834 * the _Columns table, only when the columns are from a new table
2836 if ( number == MSI_NULL_INTEGER )
2838 /* reset the column number on a new table */
2839 if (strcmpW( coltable, table ))
2841 colcol = 0;
2842 lstrcpyW( coltable, table );
2845 /* fix nul column numbers */
2846 MSI_RecordSetInteger( rec, 2, ++colcol );
2850 if (TRACE_ON(msidb)) dump_record( rec );
2852 r = msi_table_find_row( tv, rec, &row );
2853 if (r == ERROR_SUCCESS)
2855 if (!mask)
2857 TRACE("deleting row [%d]:\n", row);
2858 r = TABLE_delete_row( &tv->view, row );
2859 if (r != ERROR_SUCCESS)
2860 WARN("failed to delete row %u\n", r);
2862 else if (mask & 1)
2864 TRACE("modifying full row [%d]:\n", row);
2865 r = TABLE_set_row( &tv->view, row, rec, (1 << tv->num_cols) - 1 );
2866 if (r != ERROR_SUCCESS)
2867 WARN("failed to modify row %u\n", r);
2869 else
2871 TRACE("modifying masked row [%d]:\n", row);
2872 r = TABLE_set_row( &tv->view, row, rec, mask );
2873 if (r != ERROR_SUCCESS)
2874 WARN("failed to modify row %u\n", r);
2877 else
2879 TRACE("inserting row\n");
2880 r = TABLE_insert_row( &tv->view, rec, -1, FALSE );
2881 if (r != ERROR_SUCCESS)
2882 WARN("failed to insert row %u\n", r);
2885 if (number != MSI_NULL_INTEGER && !strcmpW( name, szColumns ))
2886 msi_update_table_columns( db, table );
2888 msiobj_release( &rec->hdr );
2891 n += sz;
2894 err:
2895 /* no need to free the table, it's associated with the database */
2896 msi_free( rawdata );
2897 if( tv )
2898 tv->view.ops->delete( &tv->view );
2900 return ERROR_SUCCESS;
2904 * msi_table_apply_transform
2906 * Enumerate the table transforms in a transform storage and apply each one.
2908 UINT msi_table_apply_transform( MSIDATABASE *db, IStorage *stg )
2910 struct list transforms;
2911 IEnumSTATSTG *stgenum = NULL;
2912 TRANSFORMDATA *transform;
2913 TRANSFORMDATA *tables = NULL, *columns = NULL;
2914 HRESULT r;
2915 STATSTG stat;
2916 string_table *strings;
2917 UINT ret = ERROR_FUNCTION_FAILED;
2918 UINT bytes_per_strref;
2920 TRACE("%p %p\n", db, stg );
2922 strings = msi_load_string_table( stg, &bytes_per_strref );
2923 if( !strings )
2924 goto end;
2926 r = IStorage_EnumElements( stg, 0, NULL, 0, &stgenum );
2927 if( FAILED( r ) )
2928 goto end;
2930 list_init(&transforms);
2932 while ( TRUE )
2934 MSITABLEVIEW *tv = NULL;
2935 WCHAR name[0x40];
2936 ULONG count = 0;
2938 r = IEnumSTATSTG_Next( stgenum, 1, &stat, &count );
2939 if ( FAILED( r ) || !count )
2940 break;
2942 decode_streamname( stat.pwcsName, name );
2943 CoTaskMemFree( stat.pwcsName );
2944 if ( name[0] != 0x4840 )
2945 continue;
2947 if ( !strcmpW( name+1, szStringPool ) ||
2948 !strcmpW( name+1, szStringData ) )
2949 continue;
2951 transform = msi_alloc_zero( sizeof(TRANSFORMDATA) );
2952 if ( !transform )
2953 break;
2955 list_add_tail( &transforms, &transform->entry );
2957 transform->name = strdupW( name + 1 );
2959 if ( !strcmpW( transform->name, szTables ) )
2960 tables = transform;
2961 else if (!strcmpW( transform->name, szColumns ) )
2962 columns = transform;
2964 TRACE("transform contains stream %s\n", debugstr_w(name));
2966 /* load the table */
2967 r = TABLE_CreateView( db, transform->name, (MSIVIEW**) &tv );
2968 if( r != ERROR_SUCCESS )
2969 continue;
2971 r = tv->view.ops->execute( &tv->view, NULL );
2972 if( r != ERROR_SUCCESS )
2974 tv->view.ops->delete( &tv->view );
2975 continue;
2978 tv->view.ops->delete( &tv->view );
2982 * Apply _Tables and _Columns transforms first so that
2983 * the table metadata is correct, and empty tables exist.
2985 ret = msi_table_load_transform( db, stg, strings, tables, bytes_per_strref );
2986 if (ret != ERROR_SUCCESS && ret != ERROR_INVALID_TABLE)
2987 goto end;
2989 ret = msi_table_load_transform( db, stg, strings, columns, bytes_per_strref );
2990 if (ret != ERROR_SUCCESS && ret != ERROR_INVALID_TABLE)
2991 goto end;
2993 ret = ERROR_SUCCESS;
2995 while ( !list_empty( &transforms ) )
2997 transform = LIST_ENTRY( list_head( &transforms ), TRANSFORMDATA, entry );
2999 if ( strcmpW( transform->name, szColumns ) &&
3000 strcmpW( transform->name, szTables ) &&
3001 ret == ERROR_SUCCESS )
3003 ret = msi_table_load_transform( db, stg, strings, transform, bytes_per_strref );
3006 list_remove( &transform->entry );
3007 msi_free( transform->name );
3008 msi_free( transform );
3011 if ( ret == ERROR_SUCCESS )
3012 append_storage_to_db( db, stg );
3014 end:
3015 if ( stgenum )
3016 IEnumSTATSTG_Release( stgenum );
3017 if ( strings )
3018 msi_destroy_stringtable( strings );
3020 return ret;