quartz: Free two assert calls from having side effects.
[wine/testsucceed.git] / dlls / msi / table.c
blobc35a95ddb816dc3fffaec2dbae2558f0b7eb279c
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 LPCWSTR tablename;
56 UINT number;
57 LPCWSTR 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 /* information for default tables */
86 static const WCHAR szTables[] = {'_','T','a','b','l','e','s',0};
87 static const WCHAR szTable[] = {'T','a','b','l','e',0};
88 static const WCHAR szColumns[] = {'_','C','o','l','u','m','n','s',0};
89 static const WCHAR szNumber[] = {'N','u','m','b','e','r',0};
90 static const WCHAR szType[] = {'T','y','p','e',0};
92 static const MSICOLUMNINFO _Columns_cols[4] = {
93 { szColumns, 1, szTable, MSITYPE_VALID | MSITYPE_STRING | MSITYPE_KEY | 64, 0, 0, 0, NULL },
94 { szColumns, 2, szNumber, MSITYPE_VALID | MSITYPE_KEY | 2, 2, 0, 0, NULL },
95 { szColumns, 3, szName, MSITYPE_VALID | MSITYPE_STRING | 64, 4, 0, 0, NULL },
96 { szColumns, 4, szType, MSITYPE_VALID | 2, 6, 0, 0, NULL },
99 static const MSICOLUMNINFO _Tables_cols[1] = {
100 { szTables, 1, szName, MSITYPE_VALID | MSITYPE_STRING | MSITYPE_KEY | 64, 0, 0, 0, NULL },
103 #define MAX_STREAM_NAME 0x1f
105 static inline UINT bytes_per_column( MSIDATABASE *db, const MSICOLUMNINFO *col, UINT bytes_per_strref )
107 if( MSITYPE_IS_BINARY(col->type) )
108 return 2;
110 if( col->type & MSITYPE_STRING )
111 return bytes_per_strref;
113 if( (col->type & 0xff) <= 2)
114 return 2;
116 if( (col->type & 0xff) != 4 )
117 ERR("Invalid column size!\n");
119 return 4;
122 static int utf2mime(int x)
124 if( (x>='0') && (x<='9') )
125 return x-'0';
126 if( (x>='A') && (x<='Z') )
127 return x-'A'+10;
128 if( (x>='a') && (x<='z') )
129 return x-'a'+10+26;
130 if( x=='.' )
131 return 10+26+26;
132 if( x=='_' )
133 return 10+26+26+1;
134 return -1;
137 LPWSTR encode_streamname(BOOL bTable, LPCWSTR in)
139 DWORD count = MAX_STREAM_NAME;
140 DWORD ch, next;
141 LPWSTR out, p;
143 if( !bTable )
144 count = lstrlenW( in )+2;
145 if (!(out = msi_alloc( count*sizeof(WCHAR) ))) return NULL;
146 p = out;
148 if( bTable )
150 *p++ = 0x4840;
151 count --;
153 while( count -- )
155 ch = *in++;
156 if( !ch )
158 *p = ch;
159 return out;
161 if( ( ch < 0x80 ) && ( utf2mime(ch) >= 0 ) )
163 ch = utf2mime(ch) + 0x4800;
164 next = *in;
165 if( next && (next<0x80) )
167 next = utf2mime(next);
168 if( next != -1 )
170 next += 0x3ffffc0;
171 ch += (next<<6);
172 in++;
176 *p++ = ch;
178 ERR("Failed to encode stream name (%s)\n",debugstr_w(in));
179 msi_free( out );
180 return NULL;
183 static int mime2utf(int x)
185 if( x<10 )
186 return x + '0';
187 if( x<(10+26))
188 return x - 10 + 'A';
189 if( x<(10+26+26))
190 return x - 10 - 26 + 'a';
191 if( x == (10+26+26) )
192 return '.';
193 return '_';
196 BOOL decode_streamname(LPCWSTR in, LPWSTR out)
198 WCHAR ch;
199 DWORD count = 0;
201 while ( (ch = *in++) )
203 if( (ch >= 0x3800 ) && (ch < 0x4840 ) )
205 if( ch >= 0x4800 )
206 ch = mime2utf(ch-0x4800);
207 else
209 ch -= 0x3800;
210 *out++ = mime2utf(ch&0x3f);
211 count++;
212 ch = mime2utf((ch>>6)&0x3f);
215 *out++ = ch;
216 count++;
218 *out = 0;
219 return count;
222 void enum_stream_names( IStorage *stg )
224 IEnumSTATSTG *stgenum = NULL;
225 HRESULT r;
226 STATSTG stat;
227 ULONG n, count;
228 WCHAR name[0x40];
230 r = IStorage_EnumElements( stg, 0, NULL, 0, &stgenum );
231 if( FAILED( r ) )
232 return;
234 n = 0;
235 while( 1 )
237 count = 0;
238 r = IEnumSTATSTG_Next( stgenum, 1, &stat, &count );
239 if( FAILED( r ) || !count )
240 break;
241 decode_streamname( stat.pwcsName, name );
242 TRACE("stream %2d -> %s %s\n", n,
243 debugstr_w(stat.pwcsName), debugstr_w(name) );
244 CoTaskMemFree( stat.pwcsName );
245 n++;
248 IEnumSTATSTG_Release( stgenum );
251 UINT read_stream_data( IStorage *stg, LPCWSTR stname, BOOL table,
252 BYTE **pdata, UINT *psz )
254 HRESULT r;
255 UINT ret = ERROR_FUNCTION_FAILED;
256 VOID *data;
257 ULONG sz, count;
258 IStream *stm = NULL;
259 STATSTG stat;
260 LPWSTR encname;
262 encname = encode_streamname(table, stname);
264 TRACE("%s -> %s\n",debugstr_w(stname),debugstr_w(encname));
266 r = IStorage_OpenStream(stg, encname, NULL,
267 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &stm);
268 msi_free( encname );
269 if( FAILED( r ) )
271 WARN("open stream failed r = %08x - empty table?\n", r);
272 return ret;
275 r = IStream_Stat(stm, &stat, STATFLAG_NONAME );
276 if( FAILED( r ) )
278 WARN("open stream failed r = %08x!\n", r);
279 goto end;
282 if( stat.cbSize.QuadPart >> 32 )
284 WARN("Too big!\n");
285 goto end;
288 sz = stat.cbSize.QuadPart;
289 data = msi_alloc( sz );
290 if( !data )
292 WARN("couldn't allocate memory r=%08x!\n", r);
293 ret = ERROR_NOT_ENOUGH_MEMORY;
294 goto end;
297 r = IStream_Read(stm, data, sz, &count );
298 if( FAILED( r ) || ( count != sz ) )
300 msi_free( data );
301 WARN("read stream failed r = %08x!\n", r);
302 goto end;
305 *pdata = data;
306 *psz = sz;
307 ret = ERROR_SUCCESS;
309 end:
310 IStream_Release( stm );
312 return ret;
315 UINT write_stream_data( IStorage *stg, LPCWSTR stname,
316 LPCVOID data, UINT sz, BOOL bTable )
318 HRESULT r;
319 UINT ret = ERROR_FUNCTION_FAILED;
320 ULONG count;
321 IStream *stm = NULL;
322 ULARGE_INTEGER size;
323 LARGE_INTEGER pos;
324 LPWSTR encname;
326 encname = encode_streamname(bTable, stname );
327 r = IStorage_OpenStream( stg, encname, NULL,
328 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, &stm);
329 if( FAILED(r) )
331 r = IStorage_CreateStream( stg, encname,
332 STGM_WRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &stm);
334 msi_free( encname );
335 if( FAILED( r ) )
337 WARN("open stream failed r = %08x\n", r);
338 return ret;
341 size.QuadPart = sz;
342 r = IStream_SetSize( stm, size );
343 if( FAILED( r ) )
345 WARN("Failed to SetSize\n");
346 goto end;
349 pos.QuadPart = 0;
350 r = IStream_Seek( stm, pos, STREAM_SEEK_SET, NULL );
351 if( FAILED( r ) )
353 WARN("Failed to Seek\n");
354 goto end;
357 if (sz)
359 r = IStream_Write(stm, data, sz, &count );
360 if( FAILED( r ) || ( count != sz ) )
362 WARN("Failed to Write\n");
363 goto end;
367 ret = ERROR_SUCCESS;
369 end:
370 IStream_Release( stm );
372 return ret;
375 static void msi_free_colinfo( MSICOLUMNINFO *colinfo, UINT count )
377 UINT i;
378 for (i = 0; i < count; i++) msi_free( colinfo[i].hash_table );
381 static void free_table( MSITABLE *table )
383 UINT i;
384 for( i=0; i<table->row_count; i++ )
385 msi_free( table->data[i] );
386 msi_free( table->data );
387 msi_free( table->data_persistent );
388 msi_free_colinfo( table->colinfo, table->col_count );
389 msi_free( table->colinfo );
390 msi_free( table );
393 static UINT msi_table_get_row_size( MSIDATABASE *db, const MSICOLUMNINFO *cols, UINT count, UINT bytes_per_strref )
395 const MSICOLUMNINFO *last_col;
397 if (!count)
398 return 0;
400 if (bytes_per_strref != LONG_STR_BYTES)
402 UINT i, size = 0;
403 for (i = 0; i < count; i++) size += bytes_per_column( db, &cols[i], bytes_per_strref );
404 return size;
406 last_col = &cols[count - 1];
407 return last_col->offset + bytes_per_column( db, last_col, bytes_per_strref );
410 /* add this table to the list of cached tables in the database */
411 static UINT read_table_from_storage( MSIDATABASE *db, MSITABLE *t, IStorage *stg )
413 BYTE *rawdata = NULL;
414 UINT rawsize = 0, i, j, row_size, row_size_mem;
416 TRACE("%s\n",debugstr_w(t->name));
418 row_size = msi_table_get_row_size( db, t->colinfo, t->col_count, db->bytes_per_strref );
419 row_size_mem = msi_table_get_row_size( db, t->colinfo, t->col_count, LONG_STR_BYTES );
421 /* if we can't read the table, just assume that it's empty */
422 read_stream_data( stg, t->name, TRUE, &rawdata, &rawsize );
423 if( !rawdata )
424 return ERROR_SUCCESS;
426 TRACE("Read %d bytes\n", rawsize );
428 if( rawsize % row_size )
430 WARN("Table size is invalid %d/%d\n", rawsize, row_size );
431 goto err;
434 t->row_count = rawsize / row_size;
435 t->data = msi_alloc_zero( t->row_count * sizeof (USHORT*) );
436 if( !t->data )
437 goto err;
438 t->data_persistent = msi_alloc_zero( t->row_count * sizeof(BOOL));
439 if ( !t->data_persistent )
440 goto err;
442 /* transpose all the data */
443 TRACE("Transposing data from %d rows\n", t->row_count );
444 for (i = 0; i < t->row_count; i++)
446 UINT ofs = 0, ofs_mem = 0;
448 t->data[i] = msi_alloc( row_size_mem );
449 if( !t->data[i] )
450 goto err;
451 t->data_persistent[i] = TRUE;
453 for (j = 0; j < t->col_count; j++)
455 UINT m = bytes_per_column( db, &t->colinfo[j], LONG_STR_BYTES );
456 UINT n = bytes_per_column( db, &t->colinfo[j], db->bytes_per_strref );
457 UINT k;
459 if ( n != 2 && n != 3 && n != 4 )
461 ERR("oops - unknown column width %d\n", n);
462 goto err;
464 if (t->colinfo[j].type & MSITYPE_STRING && n < m)
466 for (k = 0; k < m; k++)
468 if (k < n)
469 t->data[i][ofs_mem + k] = rawdata[ofs * t->row_count + i * n + k];
470 else
471 t->data[i][ofs_mem + k] = 0;
474 else
476 for (k = 0; k < n; k++)
477 t->data[i][ofs_mem + k] = rawdata[ofs * t->row_count + i * n + k];
479 ofs_mem += m;
480 ofs += n;
484 msi_free( rawdata );
485 return ERROR_SUCCESS;
486 err:
487 msi_free( rawdata );
488 return ERROR_FUNCTION_FAILED;
491 void free_cached_tables( MSIDATABASE *db )
493 while( !list_empty( &db->tables ) )
495 MSITABLE *t = LIST_ENTRY( list_head( &db->tables ), MSITABLE, entry );
497 list_remove( &t->entry );
498 free_table( t );
502 static MSITABLE *find_cached_table( MSIDATABASE *db, LPCWSTR name )
504 MSITABLE *t;
506 LIST_FOR_EACH_ENTRY( t, &db->tables, MSITABLE, entry )
507 if( !strcmpW( name, t->name ) )
508 return t;
510 return NULL;
513 static void table_calc_column_offsets( MSIDATABASE *db, MSICOLUMNINFO *colinfo, DWORD count )
515 DWORD i;
517 for (i = 0; colinfo && i < count; i++)
519 assert( i + 1 == colinfo[i].number );
520 if (i) colinfo[i].offset = colinfo[i - 1].offset +
521 bytes_per_column( db, &colinfo[i - 1], LONG_STR_BYTES );
522 else colinfo[i].offset = 0;
524 TRACE("column %d is [%s] with type %08x ofs %d\n",
525 colinfo[i].number, debugstr_w(colinfo[i].colname),
526 colinfo[i].type, colinfo[i].offset);
530 static UINT get_defaulttablecolumns( MSIDATABASE *db, LPCWSTR name, MSICOLUMNINFO *colinfo, UINT *sz )
532 const MSICOLUMNINFO *p;
533 DWORD i, n;
535 TRACE("%s\n", debugstr_w(name));
537 if (!strcmpW( name, szTables ))
539 p = _Tables_cols;
540 n = 1;
542 else if (!strcmpW( name, szColumns ))
544 p = _Columns_cols;
545 n = 4;
547 else return ERROR_FUNCTION_FAILED;
549 for (i = 0; i < n; i++)
551 if (colinfo && i < *sz) colinfo[i] = p[i];
552 if (colinfo && i >= *sz) break;
554 table_calc_column_offsets( db, colinfo, n );
555 *sz = n;
556 return ERROR_SUCCESS;
559 static UINT get_tablecolumns( MSIDATABASE *db, LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz );
561 static UINT table_get_column_info( MSIDATABASE *db, LPCWSTR name, MSICOLUMNINFO **pcols, UINT *pcount )
563 UINT r, column_count = 0;
564 MSICOLUMNINFO *columns;
566 /* get the number of columns in this table */
567 column_count = 0;
568 r = get_tablecolumns( db, name, NULL, &column_count );
569 if (r != ERROR_SUCCESS)
570 return r;
572 *pcount = column_count;
574 /* if there's no columns, there's no table */
575 if (!column_count)
576 return ERROR_INVALID_PARAMETER;
578 TRACE("table %s found\n", debugstr_w(name));
580 columns = msi_alloc( column_count * sizeof(MSICOLUMNINFO) );
581 if (!columns)
582 return ERROR_FUNCTION_FAILED;
584 r = get_tablecolumns( db, name, columns, &column_count );
585 if (r != ERROR_SUCCESS)
587 msi_free( columns );
588 return ERROR_FUNCTION_FAILED;
590 *pcols = columns;
591 return r;
594 static UINT get_table( MSIDATABASE *db, LPCWSTR name, MSITABLE **table_ret )
596 MSITABLE *table;
597 UINT r;
599 /* first, see if the table is cached */
600 table = find_cached_table( db, name );
601 if (table)
603 *table_ret = table;
604 return ERROR_SUCCESS;
607 /* nonexistent tables should be interpreted as empty tables */
608 table = msi_alloc( sizeof(MSITABLE) + lstrlenW( name ) * sizeof(WCHAR) );
609 if (!table)
610 return ERROR_FUNCTION_FAILED;
612 table->row_count = 0;
613 table->data = NULL;
614 table->data_persistent = NULL;
615 table->colinfo = NULL;
616 table->col_count = 0;
617 table->persistent = MSICONDITION_TRUE;
618 lstrcpyW( table->name, name );
620 if (!strcmpW( name, szTables ) || !strcmpW( name, szColumns ))
621 table->persistent = MSICONDITION_NONE;
623 r = table_get_column_info( db, name, &table->colinfo, &table->col_count );
624 if (r != ERROR_SUCCESS)
626 free_table( table );
627 return r;
629 r = read_table_from_storage( db, table, db->storage );
630 if (r != ERROR_SUCCESS)
632 free_table( table );
633 return r;
635 list_add_head( &db->tables, &table->entry );
636 *table_ret = table;
637 return ERROR_SUCCESS;
640 static UINT read_table_int( BYTE *const *data, UINT row, UINT col, UINT bytes )
642 UINT ret = 0, i;
644 for (i = 0; i < bytes; i++)
645 ret += data[row][col + i] << i * 8;
647 return ret;
650 static UINT get_tablecolumns( MSIDATABASE *db, LPCWSTR szTableName, MSICOLUMNINFO *colinfo, UINT *sz )
652 UINT r, i, n = 0, table_id, count, maxcount = *sz;
653 MSITABLE *table = NULL;
655 TRACE("%s\n", debugstr_w(szTableName));
657 /* first check if there is a default table with that name */
658 r = get_defaulttablecolumns( db, szTableName, colinfo, sz );
659 if (r == ERROR_SUCCESS && *sz)
660 return r;
662 r = get_table( db, szColumns, &table );
663 if (r != ERROR_SUCCESS)
665 ERR("couldn't load _Columns table\n");
666 return ERROR_FUNCTION_FAILED;
669 /* convert table and column names to IDs from the string table */
670 r = msi_string2idW( db->strings, szTableName, &table_id );
671 if (r != ERROR_SUCCESS)
673 WARN("Couldn't find id for %s\n", debugstr_w(szTableName));
674 return r;
676 TRACE("Table id is %d, row count is %d\n", table_id, table->row_count);
678 /* Note: _Columns table doesn't have non-persistent data */
680 /* if maxcount is non-zero, assume it's exactly right for this table */
681 memset( colinfo, 0, maxcount * sizeof(*colinfo) );
682 count = table->row_count;
683 for (i = 0; i < count; i++)
685 if (read_table_int( table->data, i, 0, LONG_STR_BYTES) != table_id) continue;
686 if (colinfo)
688 UINT id = read_table_int( table->data, i, table->colinfo[2].offset, LONG_STR_BYTES );
689 UINT col = read_table_int( table->data, i, table->colinfo[1].offset, sizeof(USHORT) ) - (1 << 15);
691 /* check the column number is in range */
692 if (col < 1 || col > maxcount)
694 ERR("column %d out of range\n", col);
695 continue;
697 /* check if this column was already set */
698 if (colinfo[col - 1].number)
700 ERR("duplicate column %d\n", col);
701 continue;
703 colinfo[col - 1].tablename = msi_string_lookup_id( db->strings, table_id );
704 colinfo[col - 1].number = col;
705 colinfo[col - 1].colname = msi_string_lookup_id( db->strings, id );
706 colinfo[col - 1].type = read_table_int( table->data, i, table->colinfo[3].offset,
707 sizeof(USHORT) ) - (1 << 15);
708 colinfo[col - 1].offset = 0;
709 colinfo[col - 1].ref_count = 0;
710 colinfo[col - 1].hash_table = NULL;
712 n++;
714 TRACE("%s has %d columns\n", debugstr_w(szTableName), n);
716 if (colinfo && n != maxcount)
718 ERR("missing column in table %s\n", debugstr_w(szTableName));
719 msi_free_colinfo( colinfo, maxcount );
720 return ERROR_FUNCTION_FAILED;
722 table_calc_column_offsets( db, colinfo, n );
723 *sz = n;
724 return ERROR_SUCCESS;
727 UINT msi_create_table( MSIDATABASE *db, LPCWSTR name, column_info *col_info,
728 MSICONDITION persistent )
730 enum StringPersistence string_persistence = (persistent) ? StringPersistent : StringNonPersistent;
731 UINT r, nField;
732 MSIVIEW *tv = NULL;
733 MSIRECORD *rec = NULL;
734 column_info *col;
735 MSITABLE *table;
736 UINT i;
738 /* only add tables that don't exist already */
739 if( TABLE_Exists(db, name ) )
741 WARN("table %s exists\n", debugstr_w(name));
742 return ERROR_BAD_QUERY_SYNTAX;
745 table = msi_alloc( sizeof (MSITABLE) + lstrlenW(name)*sizeof (WCHAR) );
746 if( !table )
747 return ERROR_FUNCTION_FAILED;
749 table->ref_count = 1;
750 table->row_count = 0;
751 table->data = NULL;
752 table->data_persistent = NULL;
753 table->colinfo = NULL;
754 table->col_count = 0;
755 table->persistent = persistent;
756 lstrcpyW( table->name, name );
758 for( col = col_info; col; col = col->next )
759 table->col_count++;
761 table->colinfo = msi_alloc( table->col_count * sizeof(MSICOLUMNINFO) );
762 if (!table->colinfo)
764 free_table( table );
765 return ERROR_FUNCTION_FAILED;
768 for( i = 0, col = col_info; col; i++, col = col->next )
770 UINT table_id = msi_addstringW( db->strings, col->table, -1, 1, string_persistence );
771 UINT col_id = msi_addstringW( db->strings, col->column, -1, 1, string_persistence );
773 table->colinfo[ i ].tablename = msi_string_lookup_id( db->strings, table_id );
774 table->colinfo[ i ].number = i + 1;
775 table->colinfo[ i ].colname = msi_string_lookup_id( db->strings, col_id );
776 table->colinfo[ i ].type = col->type;
777 table->colinfo[ i ].offset = 0;
778 table->colinfo[ i ].ref_count = 0;
779 table->colinfo[ i ].hash_table = NULL;
780 table->colinfo[ i ].temporary = col->temporary;
782 table_calc_column_offsets( db, table->colinfo, table->col_count);
784 r = TABLE_CreateView( db, szTables, &tv );
785 TRACE("CreateView returned %x\n", r);
786 if( r )
788 free_table( table );
789 return r;
792 r = tv->ops->execute( tv, 0 );
793 TRACE("tv execute returned %x\n", r);
794 if( r )
795 goto err;
797 rec = MSI_CreateRecord( 1 );
798 if( !rec )
799 goto err;
801 r = MSI_RecordSetStringW( rec, 1, name );
802 if( r )
803 goto err;
805 r = tv->ops->insert_row( tv, rec, -1, persistent == MSICONDITION_FALSE );
806 TRACE("insert_row returned %x\n", r);
807 if( r )
808 goto err;
810 tv->ops->delete( tv );
811 tv = NULL;
813 msiobj_release( &rec->hdr );
814 rec = NULL;
816 if( persistent != MSICONDITION_FALSE )
818 /* add each column to the _Columns table */
819 r = TABLE_CreateView( db, szColumns, &tv );
820 if( r )
821 return r;
823 r = tv->ops->execute( tv, 0 );
824 TRACE("tv execute returned %x\n", r);
825 if( r )
826 goto err;
828 rec = MSI_CreateRecord( 4 );
829 if( !rec )
830 goto err;
832 r = MSI_RecordSetStringW( rec, 1, name );
833 if( r )
834 goto err;
837 * need to set the table, column number, col name and type
838 * for each column we enter in the table
840 nField = 1;
841 for( col = col_info; col; col = col->next )
843 r = MSI_RecordSetInteger( rec, 2, nField );
844 if( r )
845 goto err;
847 r = MSI_RecordSetStringW( rec, 3, col->column );
848 if( r )
849 goto err;
851 r = MSI_RecordSetInteger( rec, 4, col->type );
852 if( r )
853 goto err;
855 r = tv->ops->insert_row( tv, rec, -1, FALSE );
856 if( r )
857 goto err;
859 nField++;
861 if( !col )
862 r = ERROR_SUCCESS;
865 err:
866 if (rec)
867 msiobj_release( &rec->hdr );
868 /* FIXME: remove values from the string table on error */
869 if( tv )
870 tv->ops->delete( tv );
872 if (r == ERROR_SUCCESS)
873 list_add_head( &db->tables, &table->entry );
874 else
875 free_table( table );
877 return r;
880 static UINT save_table( MSIDATABASE *db, const MSITABLE *t, UINT bytes_per_strref )
882 BYTE *rawdata = NULL;
883 UINT rawsize, i, j, row_size, row_count;
884 UINT r = ERROR_FUNCTION_FAILED;
886 /* Nothing to do for non-persistent tables */
887 if( t->persistent == MSICONDITION_FALSE )
888 return ERROR_SUCCESS;
890 TRACE("Saving %s\n", debugstr_w( t->name ) );
892 row_size = msi_table_get_row_size( db, t->colinfo, t->col_count, bytes_per_strref );
893 row_count = t->row_count;
894 for (i = 0; i < t->row_count; i++)
896 if (!t->data_persistent[i])
898 row_count = 1; /* yes, this is bizarre */
899 break;
902 rawsize = row_count * row_size;
903 rawdata = msi_alloc_zero( rawsize );
904 if( !rawdata )
906 r = ERROR_NOT_ENOUGH_MEMORY;
907 goto err;
910 rawsize = 0;
911 for (i = 0; i < t->row_count; i++)
913 UINT ofs = 0, ofs_mem = 0;
915 if (!t->data_persistent[i]) break;
917 for (j = 0; j < t->col_count; j++)
919 UINT m = bytes_per_column( db, &t->colinfo[j], LONG_STR_BYTES );
920 UINT n = bytes_per_column( db, &t->colinfo[j], bytes_per_strref );
921 UINT k;
923 if (n != 2 && n != 3 && n != 4)
925 ERR("oops - unknown column width %d\n", n);
926 goto err;
928 if (t->colinfo[j].type & MSITYPE_STRING && n < m)
930 UINT id = read_table_int( t->data, i, ofs_mem, LONG_STR_BYTES );
931 if (id > 1 << bytes_per_strref * 8)
933 ERR("string id %u out of range\n", id);
934 goto err;
937 for (k = 0; k < n; k++)
939 rawdata[ofs * row_count + i * n + k] = t->data[i][ofs_mem + k];
941 ofs_mem += m;
942 ofs += n;
944 rawsize += row_size;
947 TRACE("writing %d bytes\n", rawsize);
948 r = write_stream_data( db->storage, t->name, rawdata, rawsize, TRUE );
950 err:
951 msi_free( rawdata );
952 return r;
955 static void msi_update_table_columns( MSIDATABASE *db, LPCWSTR name )
957 MSITABLE *table;
958 UINT size, offset, old_count;
959 UINT n;
961 table = find_cached_table( db, name );
962 old_count = table->col_count;
963 msi_free_colinfo( table->colinfo, table->col_count );
964 msi_free( table->colinfo );
965 table->colinfo = NULL;
967 table_get_column_info( db, name, &table->colinfo, &table->col_count );
968 if (!table->col_count) return;
970 size = msi_table_get_row_size( db, table->colinfo, table->col_count, LONG_STR_BYTES );
971 offset = table->colinfo[table->col_count - 1].offset;
973 for ( n = 0; n < table->row_count; n++ )
975 table->data[n] = msi_realloc( table->data[n], size );
976 if (old_count < table->col_count)
977 memset( &table->data[n][offset], 0, size - offset );
981 /* try to find the table name in the _Tables table */
982 BOOL TABLE_Exists( MSIDATABASE *db, LPCWSTR name )
984 UINT r, table_id, i;
985 MSITABLE *table;
987 if( !strcmpW( name, szTables ) || !strcmpW( name, szColumns ) ||
988 !strcmpW( name, szStreams ) || !strcmpW( name, szStorages ) )
989 return TRUE;
991 r = msi_string2idW( db->strings, name, &table_id );
992 if( r != ERROR_SUCCESS )
994 TRACE("Couldn't find id for %s\n", debugstr_w(name));
995 return FALSE;
998 r = get_table( db, szTables, &table );
999 if( r != ERROR_SUCCESS )
1001 ERR("table %s not available\n", debugstr_w(szTables));
1002 return FALSE;
1005 for( i = 0; i < table->row_count; i++ )
1007 if( read_table_int( table->data, i, 0, LONG_STR_BYTES ) == table_id )
1008 return TRUE;
1011 return FALSE;
1014 /* below is the query interface to a table */
1016 typedef struct tagMSITABLEVIEW
1018 MSIVIEW view;
1019 MSIDATABASE *db;
1020 MSITABLE *table;
1021 MSICOLUMNINFO *columns;
1022 MSIORDERINFO *order;
1023 UINT num_cols;
1024 UINT row_size;
1025 WCHAR name[1];
1026 } MSITABLEVIEW;
1028 static UINT TABLE_fetch_int( struct tagMSIVIEW *view, UINT row, UINT col, UINT *val )
1030 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1031 UINT offset, n;
1033 if( !tv->table )
1034 return ERROR_INVALID_PARAMETER;
1036 if( (col==0) || (col>tv->num_cols) )
1037 return ERROR_INVALID_PARAMETER;
1039 /* how many rows are there ? */
1040 if( row >= tv->table->row_count )
1041 return ERROR_NO_MORE_ITEMS;
1043 if( tv->columns[col-1].offset >= tv->row_size )
1045 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1046 ERR("%p %p\n", tv, tv->columns );
1047 return ERROR_FUNCTION_FAILED;
1050 if (tv->order)
1051 row = tv->order->reorder[row];
1053 n = bytes_per_column( tv->db, &tv->columns[col - 1], LONG_STR_BYTES );
1054 if (n != 2 && n != 3 && n != 4)
1056 ERR("oops! what is %d bytes per column?\n", n );
1057 return ERROR_FUNCTION_FAILED;
1060 offset = tv->columns[col-1].offset;
1061 *val = read_table_int(tv->table->data, row, offset, n);
1063 /* TRACE("Data [%d][%d] = %d\n", row, col, *val ); */
1065 return ERROR_SUCCESS;
1068 static UINT msi_stream_name( const MSITABLEVIEW *tv, UINT row, LPWSTR *pstname )
1070 LPWSTR p, stname = NULL;
1071 UINT i, r, type, ival;
1072 DWORD len;
1073 LPCWSTR sval;
1074 MSIVIEW *view = (MSIVIEW *) tv;
1076 TRACE("%p %d\n", tv, row);
1078 len = lstrlenW( tv->name ) + 1;
1079 stname = msi_alloc( len*sizeof(WCHAR) );
1080 if ( !stname )
1082 r = ERROR_OUTOFMEMORY;
1083 goto err;
1086 lstrcpyW( stname, tv->name );
1088 for ( i = 0; i < tv->num_cols; i++ )
1090 type = tv->columns[i].type;
1091 if ( type & MSITYPE_KEY )
1093 WCHAR number[0x20];
1095 r = TABLE_fetch_int( view, row, i+1, &ival );
1096 if ( r != ERROR_SUCCESS )
1097 goto err;
1099 if ( tv->columns[i].type & MSITYPE_STRING )
1101 sval = msi_string_lookup_id( tv->db->strings, ival );
1102 if ( !sval )
1104 r = ERROR_INVALID_PARAMETER;
1105 goto err;
1108 else
1110 static const WCHAR fmt[] = { '%','d',0 };
1111 UINT n = bytes_per_column( tv->db, &tv->columns[i], LONG_STR_BYTES );
1113 switch( n )
1115 case 2:
1116 sprintfW( number, fmt, ival-0x8000 );
1117 break;
1118 case 4:
1119 sprintfW( number, fmt, ival^0x80000000 );
1120 break;
1121 default:
1122 ERR( "oops - unknown column width %d\n", n );
1123 r = ERROR_FUNCTION_FAILED;
1124 goto err;
1126 sval = number;
1129 len += lstrlenW( szDot ) + lstrlenW( sval );
1130 p = msi_realloc ( stname, len*sizeof(WCHAR) );
1131 if ( !p )
1133 r = ERROR_OUTOFMEMORY;
1134 goto err;
1136 stname = p;
1138 lstrcatW( stname, szDot );
1139 lstrcatW( stname, sval );
1141 else
1142 continue;
1145 *pstname = stname;
1146 return ERROR_SUCCESS;
1148 err:
1149 msi_free( stname );
1150 *pstname = NULL;
1151 return r;
1155 * We need a special case for streams, as we need to reference column with
1156 * the name of the stream in the same table, and the table name
1157 * which may not be available at higher levels of the query
1159 static UINT TABLE_fetch_stream( struct tagMSIVIEW *view, UINT row, UINT col, IStream **stm )
1161 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1162 UINT r;
1163 LPWSTR encname, full_name = NULL;
1165 if( !view->ops->fetch_int )
1166 return ERROR_INVALID_PARAMETER;
1168 r = msi_stream_name( tv, row, &full_name );
1169 if ( r != ERROR_SUCCESS )
1171 ERR("fetching stream, error = %d\n", r);
1172 return r;
1175 encname = encode_streamname( FALSE, full_name );
1176 r = msi_get_raw_stream( tv->db, encname, stm );
1177 if( r )
1178 ERR("fetching stream %s, error = %d\n",debugstr_w(full_name), r);
1180 msi_free( full_name );
1181 msi_free( encname );
1182 return r;
1185 static UINT TABLE_set_int( MSITABLEVIEW *tv, UINT row, UINT col, UINT val )
1187 UINT offset, n, i;
1189 if( !tv->table )
1190 return ERROR_INVALID_PARAMETER;
1192 if( (col==0) || (col>tv->num_cols) )
1193 return ERROR_INVALID_PARAMETER;
1195 if( row >= tv->table->row_count )
1196 return ERROR_INVALID_PARAMETER;
1198 if( tv->columns[col-1].offset >= tv->row_size )
1200 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1201 ERR("%p %p\n", tv, tv->columns );
1202 return ERROR_FUNCTION_FAILED;
1205 msi_free( tv->columns[col-1].hash_table );
1206 tv->columns[col-1].hash_table = NULL;
1208 n = bytes_per_column( tv->db, &tv->columns[col - 1], LONG_STR_BYTES );
1209 if ( n != 2 && n != 3 && n != 4 )
1211 ERR("oops! what is %d bytes per column?\n", n );
1212 return ERROR_FUNCTION_FAILED;
1215 offset = tv->columns[col-1].offset;
1216 for ( i = 0; i < n; i++ )
1217 tv->table->data[row][offset + i] = (val >> i * 8) & 0xff;
1219 return ERROR_SUCCESS;
1222 static UINT TABLE_get_row( struct tagMSIVIEW *view, UINT row, MSIRECORD **rec )
1224 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1226 if (!tv->table)
1227 return ERROR_INVALID_PARAMETER;
1229 if (tv->order)
1230 row = tv->order->reorder[row];
1232 return msi_view_get_row(tv->db, view, row, rec);
1235 static UINT msi_addstreamW( MSIDATABASE *db, LPCWSTR name, IStream *data )
1237 static const WCHAR insert[] = {
1238 'I','N','S','E','R','T',' ','I','N','T','O',' ',
1239 '`','_','S','t','r','e','a','m','s','`',' ',
1240 '(','`','N','a','m','e','`',',','`','D','a','t','a','`',')',' ',
1241 'V','A','L','U','E','S',' ','(','?',',','?',')',0};
1242 MSIQUERY *query = NULL;
1243 MSIRECORD *rec;
1244 UINT r;
1246 TRACE("%p %s %p\n", db, debugstr_w(name), data);
1248 rec = MSI_CreateRecord( 2 );
1249 if ( !rec )
1250 return ERROR_OUTOFMEMORY;
1252 r = MSI_RecordSetStringW( rec, 1, name );
1253 if ( r != ERROR_SUCCESS )
1254 goto err;
1256 r = MSI_RecordSetIStream( rec, 2, data );
1257 if ( r != ERROR_SUCCESS )
1258 goto err;
1260 r = MSI_DatabaseOpenViewW( db, insert, &query );
1261 if ( r != ERROR_SUCCESS )
1262 goto err;
1264 r = MSI_ViewExecute( query, rec );
1266 err:
1267 msiobj_release( &query->hdr );
1268 msiobj_release( &rec->hdr );
1269 return r;
1272 static UINT get_table_value_from_record( MSITABLEVIEW *tv, MSIRECORD *rec, UINT iField, UINT *pvalue )
1274 MSICOLUMNINFO columninfo;
1275 UINT r;
1277 if ( (iField <= 0) ||
1278 (iField > tv->num_cols) ||
1279 MSI_RecordIsNull( rec, iField ) )
1280 return ERROR_FUNCTION_FAILED;
1282 columninfo = tv->columns[ iField - 1 ];
1284 if ( MSITYPE_IS_BINARY(columninfo.type) )
1286 *pvalue = 1; /* refers to the first key column */
1288 else if ( columninfo.type & MSITYPE_STRING )
1290 LPCWSTR sval = MSI_RecordGetString( rec, iField );
1291 if (sval)
1293 r = msi_string2idW(tv->db->strings, sval, pvalue);
1294 if (r != ERROR_SUCCESS)
1295 return ERROR_NOT_FOUND;
1297 else *pvalue = 0;
1299 else if ( bytes_per_column( tv->db, &columninfo, LONG_STR_BYTES ) == 2 )
1301 *pvalue = 0x8000 + MSI_RecordGetInteger( rec, iField );
1302 if ( *pvalue & 0xffff0000 )
1304 ERR("field %u value %d out of range\n", iField, *pvalue - 0x8000);
1305 return ERROR_FUNCTION_FAILED;
1308 else
1310 INT ival = MSI_RecordGetInteger( rec, iField );
1311 *pvalue = ival ^ 0x80000000;
1314 return ERROR_SUCCESS;
1317 static UINT TABLE_set_row( struct tagMSIVIEW *view, UINT row, MSIRECORD *rec, UINT mask )
1319 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1320 UINT i, val, r = ERROR_SUCCESS;
1322 if ( !tv->table )
1323 return ERROR_INVALID_PARAMETER;
1325 /* test if any of the mask bits are invalid */
1326 if ( mask >= (1<<tv->num_cols) )
1327 return ERROR_INVALID_PARAMETER;
1329 for ( i = 0; i < tv->num_cols; i++ )
1331 BOOL persistent;
1333 /* only update the fields specified in the mask */
1334 if ( !(mask&(1<<i)) )
1335 continue;
1337 persistent = (tv->table->persistent != MSICONDITION_FALSE) &&
1338 (tv->table->data_persistent[row]);
1339 /* FIXME: should we allow updating keys? */
1341 val = 0;
1342 if ( !MSI_RecordIsNull( rec, i + 1 ) )
1344 r = get_table_value_from_record (tv, rec, i + 1, &val);
1345 if ( MSITYPE_IS_BINARY(tv->columns[ i ].type) )
1347 IStream *stm;
1348 LPWSTR stname;
1350 if ( r != ERROR_SUCCESS )
1351 return ERROR_FUNCTION_FAILED;
1353 r = MSI_RecordGetIStream( rec, i + 1, &stm );
1354 if ( r != ERROR_SUCCESS )
1355 return r;
1357 r = msi_stream_name( tv, row, &stname );
1358 if ( r != ERROR_SUCCESS )
1360 IStream_Release( stm );
1361 return r;
1364 r = msi_addstreamW( tv->db, stname, stm );
1365 IStream_Release( stm );
1366 msi_free ( stname );
1368 if ( r != ERROR_SUCCESS )
1369 return r;
1371 else if ( tv->columns[i].type & MSITYPE_STRING )
1373 UINT x;
1375 if ( r != ERROR_SUCCESS )
1377 LPCWSTR sval = MSI_RecordGetString( rec, i + 1 );
1378 val = msi_addstringW( tv->db->strings, sval, -1, 1,
1379 persistent ? StringPersistent : StringNonPersistent );
1381 else
1383 TABLE_fetch_int(&tv->view, row, i + 1, &x);
1384 if (val == x)
1385 continue;
1388 else
1390 if ( r != ERROR_SUCCESS )
1391 return ERROR_FUNCTION_FAILED;
1395 r = TABLE_set_int( tv, row, i+1, val );
1396 if ( r != ERROR_SUCCESS )
1397 break;
1399 return r;
1402 static UINT table_create_new_row( struct tagMSIVIEW *view, UINT *num, BOOL temporary )
1404 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1405 BYTE **p, *row;
1406 BOOL *b;
1407 UINT sz;
1408 BYTE ***data_ptr;
1409 BOOL **data_persist_ptr;
1410 UINT *row_count;
1412 TRACE("%p %s\n", view, temporary ? "TRUE" : "FALSE");
1414 if( !tv->table )
1415 return ERROR_INVALID_PARAMETER;
1417 row = msi_alloc_zero( tv->row_size );
1418 if( !row )
1419 return ERROR_NOT_ENOUGH_MEMORY;
1421 row_count = &tv->table->row_count;
1422 data_ptr = &tv->table->data;
1423 data_persist_ptr = &tv->table->data_persistent;
1424 if (*num == -1)
1425 *num = tv->table->row_count;
1427 sz = (*row_count + 1) * sizeof (BYTE*);
1428 if( *data_ptr )
1429 p = msi_realloc( *data_ptr, sz );
1430 else
1431 p = msi_alloc( sz );
1432 if( !p )
1434 msi_free( row );
1435 return ERROR_NOT_ENOUGH_MEMORY;
1438 sz = (*row_count + 1) * sizeof (BOOL);
1439 if( *data_persist_ptr )
1440 b = msi_realloc( *data_persist_ptr, sz );
1441 else
1442 b = msi_alloc( sz );
1443 if( !b )
1445 msi_free( row );
1446 msi_free( p );
1447 return ERROR_NOT_ENOUGH_MEMORY;
1450 *data_ptr = p;
1451 (*data_ptr)[*row_count] = row;
1453 *data_persist_ptr = b;
1454 (*data_persist_ptr)[*row_count] = !temporary;
1456 (*row_count)++;
1458 return ERROR_SUCCESS;
1461 static UINT TABLE_execute( struct tagMSIVIEW *view, MSIRECORD *record )
1463 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1465 TRACE("%p %p\n", tv, record);
1467 TRACE("There are %d columns\n", tv->num_cols );
1469 return ERROR_SUCCESS;
1472 static UINT TABLE_close( struct tagMSIVIEW *view )
1474 TRACE("%p\n", view );
1476 return ERROR_SUCCESS;
1479 static UINT TABLE_get_dimensions( struct tagMSIVIEW *view, UINT *rows, UINT *cols)
1481 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1483 TRACE("%p %p %p\n", view, rows, cols );
1485 if( cols )
1486 *cols = tv->num_cols;
1487 if( rows )
1489 if( !tv->table )
1490 return ERROR_INVALID_PARAMETER;
1491 *rows = tv->table->row_count;
1494 return ERROR_SUCCESS;
1497 static UINT TABLE_get_column_info( struct tagMSIVIEW *view,
1498 UINT n, LPCWSTR *name, UINT *type, BOOL *temporary,
1499 LPCWSTR *table_name )
1501 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1503 TRACE("%p %d %p %p\n", tv, n, name, type );
1505 if( ( n == 0 ) || ( n > tv->num_cols ) )
1506 return ERROR_INVALID_PARAMETER;
1508 if( name )
1510 *name = tv->columns[n-1].colname;
1511 if( !*name )
1512 return ERROR_FUNCTION_FAILED;
1515 if( table_name )
1517 *table_name = tv->columns[n-1].tablename;
1518 if( !*table_name )
1519 return ERROR_FUNCTION_FAILED;
1522 if( type )
1523 *type = tv->columns[n-1].type;
1525 if( temporary )
1526 *temporary = tv->columns[n-1].temporary;
1528 return ERROR_SUCCESS;
1531 static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row, UINT *column );
1533 static UINT table_validate_new( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *column )
1535 UINT r, row, i;
1537 /* check there's no null values where they're not allowed */
1538 for( i = 0; i < tv->num_cols; i++ )
1540 if ( tv->columns[i].type & MSITYPE_NULLABLE )
1541 continue;
1543 if ( MSITYPE_IS_BINARY(tv->columns[i].type) )
1544 TRACE("skipping binary column\n");
1545 else if ( tv->columns[i].type & MSITYPE_STRING )
1547 LPCWSTR str;
1549 str = MSI_RecordGetString( rec, i+1 );
1550 if (str == NULL || str[0] == 0)
1552 if (column) *column = i;
1553 return ERROR_INVALID_DATA;
1556 else
1558 UINT n;
1560 n = MSI_RecordGetInteger( rec, i+1 );
1561 if (n == MSI_NULL_INTEGER)
1563 if (column) *column = i;
1564 return ERROR_INVALID_DATA;
1569 /* check there's no duplicate keys */
1570 r = msi_table_find_row( tv, rec, &row, column );
1571 if (r == ERROR_SUCCESS)
1572 return ERROR_FUNCTION_FAILED;
1574 return ERROR_SUCCESS;
1577 static int compare_record( MSITABLEVIEW *tv, UINT row, MSIRECORD *rec )
1579 UINT r, i, ivalue, x;
1581 for (i = 0; i < tv->num_cols; i++ )
1583 if (!(tv->columns[i].type & MSITYPE_KEY)) continue;
1585 r = get_table_value_from_record( tv, rec, i + 1, &ivalue );
1586 if (r != ERROR_SUCCESS)
1587 return 1;
1589 r = TABLE_fetch_int( &tv->view, row, i + 1, &x );
1590 if (r != ERROR_SUCCESS)
1592 WARN("TABLE_fetch_int should not fail here %u\n", r);
1593 return -1;
1595 if (ivalue > x)
1597 return 1;
1599 else if (ivalue == x)
1601 if (i < tv->num_cols - 1) continue;
1602 return 0;
1604 else
1605 return -1;
1607 return 1;
1610 static int find_insert_index( MSITABLEVIEW *tv, MSIRECORD *rec )
1612 int idx, c, low = 0, high = tv->table->row_count - 1;
1614 TRACE("%p %p\n", tv, rec);
1616 while (low <= high)
1618 idx = (low + high) / 2;
1619 c = compare_record( tv, idx, rec );
1621 if (c < 0)
1622 high = idx - 1;
1623 else if (c > 0)
1624 low = idx + 1;
1625 else
1627 TRACE("found %u\n", idx);
1628 return idx;
1631 TRACE("found %u\n", high + 1);
1632 return high + 1;
1635 static UINT TABLE_insert_row( struct tagMSIVIEW *view, MSIRECORD *rec, UINT row, BOOL temporary )
1637 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1638 UINT i, r;
1640 TRACE("%p %p %s\n", tv, rec, temporary ? "TRUE" : "FALSE" );
1642 /* check that the key is unique - can we find a matching row? */
1643 r = table_validate_new( tv, rec, NULL );
1644 if( r != ERROR_SUCCESS )
1645 return ERROR_FUNCTION_FAILED;
1647 if (row == -1)
1648 row = find_insert_index( tv, rec );
1650 r = table_create_new_row( view, &row, temporary );
1651 TRACE("insert_row returned %08x\n", r);
1652 if( r != ERROR_SUCCESS )
1653 return r;
1655 /* shift the rows to make room for the new row */
1656 for (i = tv->table->row_count - 1; i > row; i--)
1658 memmove(&(tv->table->data[i][0]),
1659 &(tv->table->data[i - 1][0]), tv->row_size);
1660 tv->table->data_persistent[i] = tv->table->data_persistent[i - 1];
1663 /* Re-set the persistence flag */
1664 tv->table->data_persistent[row] = !temporary;
1665 return TABLE_set_row( view, row, rec, (1<<tv->num_cols) - 1 );
1668 static UINT TABLE_delete_row( struct tagMSIVIEW *view, UINT row )
1670 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1671 UINT r, num_rows, num_cols, i;
1673 TRACE("%p %d\n", tv, row);
1675 if ( !tv->table )
1676 return ERROR_INVALID_PARAMETER;
1678 r = TABLE_get_dimensions( view, &num_rows, &num_cols );
1679 if ( r != ERROR_SUCCESS )
1680 return r;
1682 if ( row >= num_rows )
1683 return ERROR_FUNCTION_FAILED;
1685 num_rows = tv->table->row_count;
1686 tv->table->row_count--;
1688 /* reset the hash tables */
1689 for (i = 0; i < tv->num_cols; i++)
1691 msi_free( tv->columns[i].hash_table );
1692 tv->columns[i].hash_table = NULL;
1695 for (i = row + 1; i < num_rows; i++)
1697 memcpy(tv->table->data[i - 1], tv->table->data[i], tv->row_size);
1698 tv->table->data_persistent[i - 1] = tv->table->data_persistent[i];
1701 msi_free(tv->table->data[num_rows - 1]);
1703 return ERROR_SUCCESS;
1706 static UINT msi_table_update(struct tagMSIVIEW *view, MSIRECORD *rec, UINT row)
1708 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1709 UINT r, new_row;
1711 /* FIXME: MsiViewFetch should set rec index 0 to some ID that
1712 * sets the fetched record apart from other records
1715 if (!tv->table)
1716 return ERROR_INVALID_PARAMETER;
1718 r = msi_table_find_row(tv, rec, &new_row, NULL);
1719 if (r != ERROR_SUCCESS)
1721 ERR("can't find row to modify\n");
1722 return ERROR_FUNCTION_FAILED;
1725 /* the row cannot be changed */
1726 if (row != new_row + 1)
1727 return ERROR_FUNCTION_FAILED;
1729 if(tv->order)
1730 new_row = tv->order->reorder[new_row];
1732 return TABLE_set_row(view, new_row, rec, (1 << tv->num_cols) - 1);
1735 static UINT msi_table_assign(struct tagMSIVIEW *view, MSIRECORD *rec)
1737 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1738 UINT r, row;
1740 if (!tv->table)
1741 return ERROR_INVALID_PARAMETER;
1743 r = msi_table_find_row(tv, rec, &row, NULL);
1744 if (r == ERROR_SUCCESS)
1745 return TABLE_set_row(view, row, rec, (1 << tv->num_cols) - 1);
1746 else
1747 return TABLE_insert_row( view, rec, -1, FALSE );
1750 static UINT modify_delete_row( struct tagMSIVIEW *view, MSIRECORD *rec )
1752 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
1753 UINT row, r;
1755 r = msi_table_find_row(tv, rec, &row, NULL);
1756 if (r != ERROR_SUCCESS)
1757 return r;
1759 return TABLE_delete_row(view, row);
1762 static UINT msi_refresh_record( struct tagMSIVIEW *view, MSIRECORD *rec, UINT row )
1764 MSIRECORD *curr;
1765 UINT r, i, count;
1767 r = TABLE_get_row(view, row - 1, &curr);
1768 if (r != ERROR_SUCCESS)
1769 return r;
1771 /* Close the original record */
1772 MSI_CloseRecord(&rec->hdr);
1774 count = MSI_RecordGetFieldCount(rec);
1775 for (i = 0; i < count; i++)
1776 MSI_RecordCopyField(curr, i + 1, rec, i + 1);
1778 msiobj_release(&curr->hdr);
1779 return ERROR_SUCCESS;
1782 static UINT TABLE_modify( struct tagMSIVIEW *view, MSIMODIFY eModifyMode,
1783 MSIRECORD *rec, UINT row)
1785 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1786 UINT r, column;
1788 TRACE("%p %d %p\n", view, eModifyMode, rec );
1790 switch (eModifyMode)
1792 case MSIMODIFY_DELETE:
1793 r = modify_delete_row( view, rec );
1794 break;
1795 case MSIMODIFY_VALIDATE_NEW:
1796 r = table_validate_new( tv, rec, &column );
1797 if (r != ERROR_SUCCESS)
1799 tv->view.error = MSIDBERROR_DUPLICATEKEY;
1800 tv->view.error_column = tv->columns[column].colname;
1801 r = ERROR_INVALID_DATA;
1803 break;
1805 case MSIMODIFY_INSERT:
1806 r = table_validate_new( tv, rec, NULL );
1807 if (r != ERROR_SUCCESS)
1808 break;
1809 r = TABLE_insert_row( view, rec, -1, FALSE );
1810 break;
1812 case MSIMODIFY_INSERT_TEMPORARY:
1813 r = table_validate_new( tv, rec, NULL );
1814 if (r != ERROR_SUCCESS)
1815 break;
1816 r = TABLE_insert_row( view, rec, -1, TRUE );
1817 break;
1819 case MSIMODIFY_REFRESH:
1820 r = msi_refresh_record( view, rec, row );
1821 break;
1823 case MSIMODIFY_UPDATE:
1824 r = msi_table_update( view, rec, row );
1825 break;
1827 case MSIMODIFY_ASSIGN:
1828 r = msi_table_assign( view, rec );
1829 break;
1831 case MSIMODIFY_REPLACE:
1832 case MSIMODIFY_MERGE:
1833 case MSIMODIFY_VALIDATE:
1834 case MSIMODIFY_VALIDATE_FIELD:
1835 case MSIMODIFY_VALIDATE_DELETE:
1836 FIXME("%p %d %p - mode not implemented\n", view, eModifyMode, rec );
1837 r = ERROR_CALL_NOT_IMPLEMENTED;
1838 break;
1840 default:
1841 r = ERROR_INVALID_DATA;
1844 return r;
1847 static UINT TABLE_delete( struct tagMSIVIEW *view )
1849 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1851 TRACE("%p\n", view );
1853 tv->table = NULL;
1854 tv->columns = NULL;
1856 if (tv->order)
1858 msi_free( tv->order->reorder );
1859 msi_free( tv->order );
1860 tv->order = NULL;
1863 msi_free( tv );
1865 return ERROR_SUCCESS;
1868 static UINT TABLE_find_matching_rows( struct tagMSIVIEW *view, UINT col,
1869 UINT val, UINT *row, MSIITERHANDLE *handle )
1871 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1872 const MSICOLUMNHASHENTRY *entry;
1874 TRACE("%p, %d, %u, %p\n", view, col, val, *handle);
1876 if( !tv->table )
1877 return ERROR_INVALID_PARAMETER;
1879 if( (col==0) || (col > tv->num_cols) )
1880 return ERROR_INVALID_PARAMETER;
1882 if( !tv->columns[col-1].hash_table )
1884 UINT i;
1885 UINT num_rows = tv->table->row_count;
1886 MSICOLUMNHASHENTRY **hash_table;
1887 MSICOLUMNHASHENTRY *new_entry;
1889 if( tv->columns[col-1].offset >= tv->row_size )
1891 ERR("Stuffed up %d >= %d\n", tv->columns[col-1].offset, tv->row_size );
1892 ERR("%p %p\n", tv, tv->columns );
1893 return ERROR_FUNCTION_FAILED;
1896 /* allocate contiguous memory for the table and its entries so we
1897 * don't have to do an expensive cleanup */
1898 hash_table = msi_alloc(MSITABLE_HASH_TABLE_SIZE * sizeof(MSICOLUMNHASHENTRY*) +
1899 num_rows * sizeof(MSICOLUMNHASHENTRY));
1900 if (!hash_table)
1901 return ERROR_OUTOFMEMORY;
1903 memset(hash_table, 0, MSITABLE_HASH_TABLE_SIZE * sizeof(MSICOLUMNHASHENTRY*));
1904 tv->columns[col-1].hash_table = hash_table;
1906 new_entry = (MSICOLUMNHASHENTRY *)(hash_table + MSITABLE_HASH_TABLE_SIZE);
1908 for (i = 0; i < num_rows; i++, new_entry++)
1910 UINT row_value;
1912 if (view->ops->fetch_int( view, i, col, &row_value ) != ERROR_SUCCESS)
1913 continue;
1915 new_entry->next = NULL;
1916 new_entry->value = row_value;
1917 new_entry->row = i;
1918 if (hash_table[row_value % MSITABLE_HASH_TABLE_SIZE])
1920 MSICOLUMNHASHENTRY *prev_entry = hash_table[row_value % MSITABLE_HASH_TABLE_SIZE];
1921 while (prev_entry->next)
1922 prev_entry = prev_entry->next;
1923 prev_entry->next = new_entry;
1925 else
1926 hash_table[row_value % MSITABLE_HASH_TABLE_SIZE] = new_entry;
1930 if( !*handle )
1931 entry = tv->columns[col-1].hash_table[val % MSITABLE_HASH_TABLE_SIZE];
1932 else
1933 entry = (*handle)->next;
1935 while (entry && entry->value != val)
1936 entry = entry->next;
1938 *handle = entry;
1939 if (!entry)
1940 return ERROR_NO_MORE_ITEMS;
1942 *row = entry->row;
1944 return ERROR_SUCCESS;
1947 static UINT TABLE_add_ref(struct tagMSIVIEW *view)
1949 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1950 UINT i;
1952 TRACE("%p %d\n", view, tv->table->ref_count);
1954 for (i = 0; i < tv->table->col_count; i++)
1956 if (tv->table->colinfo[i].type & MSITYPE_TEMPORARY)
1957 InterlockedIncrement(&tv->table->colinfo[i].ref_count);
1960 return InterlockedIncrement(&tv->table->ref_count);
1963 static UINT TABLE_remove_column(struct tagMSIVIEW *view, LPCWSTR table, UINT number)
1965 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
1966 MSIRECORD *rec = NULL;
1967 MSIVIEW *columns = NULL;
1968 UINT row, r;
1970 rec = MSI_CreateRecord(2);
1971 if (!rec)
1972 return ERROR_OUTOFMEMORY;
1974 MSI_RecordSetStringW(rec, 1, table);
1975 MSI_RecordSetInteger(rec, 2, number);
1977 r = TABLE_CreateView(tv->db, szColumns, &columns);
1978 if (r != ERROR_SUCCESS)
1979 return r;
1981 r = msi_table_find_row((MSITABLEVIEW *)columns, rec, &row, NULL);
1982 if (r != ERROR_SUCCESS)
1983 goto done;
1985 r = TABLE_delete_row(columns, row);
1986 if (r != ERROR_SUCCESS)
1987 goto done;
1989 msi_update_table_columns(tv->db, table);
1991 done:
1992 msiobj_release(&rec->hdr);
1993 columns->ops->delete(columns);
1994 return r;
1997 static UINT TABLE_release(struct tagMSIVIEW *view)
1999 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2000 INT ref = tv->table->ref_count;
2001 UINT i, r;
2003 TRACE("%p %d\n", view, ref);
2005 for (i = 0; i < tv->table->col_count; i++)
2007 if (tv->table->colinfo[i].type & MSITYPE_TEMPORARY)
2009 ref = InterlockedDecrement(&tv->table->colinfo[i].ref_count);
2010 if (ref == 0)
2012 r = TABLE_remove_column(view, tv->table->colinfo[i].tablename,
2013 tv->table->colinfo[i].number);
2014 if (r != ERROR_SUCCESS)
2015 break;
2020 ref = InterlockedDecrement(&tv->table->ref_count);
2021 if (ref == 0)
2023 if (!tv->table->row_count)
2025 list_remove(&tv->table->entry);
2026 free_table(tv->table);
2027 TABLE_delete(view);
2031 return ref;
2034 static UINT TABLE_add_column(struct tagMSIVIEW *view, LPCWSTR table, UINT number,
2035 LPCWSTR column, UINT type, BOOL hold)
2037 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2038 MSITABLE *msitable;
2039 MSIRECORD *rec;
2040 UINT r, i;
2042 rec = MSI_CreateRecord(4);
2043 if (!rec)
2044 return ERROR_OUTOFMEMORY;
2046 MSI_RecordSetStringW(rec, 1, table);
2047 MSI_RecordSetInteger(rec, 2, number);
2048 MSI_RecordSetStringW(rec, 3, column);
2049 MSI_RecordSetInteger(rec, 4, type);
2051 r = TABLE_insert_row(&tv->view, rec, -1, FALSE);
2052 if (r != ERROR_SUCCESS)
2053 goto done;
2055 msi_update_table_columns(tv->db, table);
2057 if (!hold)
2058 goto done;
2060 msitable = find_cached_table(tv->db, table);
2061 for (i = 0; i < msitable->col_count; i++)
2063 if (!strcmpW( msitable->colinfo[i].colname, column ))
2065 InterlockedIncrement(&msitable->colinfo[i].ref_count);
2066 break;
2070 done:
2071 msiobj_release(&rec->hdr);
2072 return r;
2075 static UINT order_add_column(struct tagMSIVIEW *view, MSIORDERINFO *order, LPCWSTR name)
2077 UINT n, r, count;
2078 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2080 r = TABLE_get_dimensions(view, NULL, &count);
2081 if (r != ERROR_SUCCESS)
2082 return r;
2084 if (order->num_cols >= count)
2085 return ERROR_FUNCTION_FAILED;
2087 r = VIEW_find_column(view, name, tv->name, &n);
2088 if (r != ERROR_SUCCESS)
2089 return r;
2091 order->cols[order->num_cols] = n;
2092 TRACE("Ordering by column %s (%d)\n", debugstr_w(name), n);
2094 order->num_cols++;
2096 return ERROR_SUCCESS;
2099 static UINT order_compare(struct tagMSIVIEW *view, MSIORDERINFO *order,
2100 UINT a, UINT b, UINT *swap)
2102 UINT r, i, a_val = 0, b_val = 0;
2104 *swap = 0;
2105 for (i = 0; i < order->num_cols; i++)
2107 r = TABLE_fetch_int(view, a, order->cols[i], &a_val);
2108 if (r != ERROR_SUCCESS)
2109 return r;
2111 r = TABLE_fetch_int(view, b, order->cols[i], &b_val);
2112 if (r != ERROR_SUCCESS)
2113 return r;
2115 if (a_val != b_val)
2117 if (a_val > b_val)
2118 *swap = 1;
2119 break;
2123 return ERROR_SUCCESS;
2126 static UINT order_mergesort(struct tagMSIVIEW *view, MSIORDERINFO *order,
2127 UINT left, UINT right)
2129 UINT r, i, j, temp;
2130 UINT swap = 0, center = (left + right) / 2;
2131 UINT *array = order->reorder;
2133 if (left == right)
2134 return ERROR_SUCCESS;
2136 /* sort the left half */
2137 r = order_mergesort(view, order, left, center);
2138 if (r != ERROR_SUCCESS)
2139 return r;
2141 /* sort the right half */
2142 r = order_mergesort(view, order, center + 1, right);
2143 if (r != ERROR_SUCCESS)
2144 return r;
2146 for (i = left, j = center + 1; (i <= center) && (j <= right); i++)
2148 r = order_compare(view, order, array[i], array[j], &swap);
2149 if (r != ERROR_SUCCESS)
2150 return r;
2152 if (swap)
2154 temp = array[j];
2155 memmove(&array[i + 1], &array[i], (j - i) * sizeof(UINT));
2156 array[i] = temp;
2157 j++;
2158 center++;
2162 return ERROR_SUCCESS;
2165 static UINT order_verify(struct tagMSIVIEW *view, MSIORDERINFO *order, UINT num_rows)
2167 UINT i, swap, r;
2169 for (i = 1; i < num_rows; i++)
2171 r = order_compare(view, order, order->reorder[i - 1],
2172 order->reorder[i], &swap);
2173 if (r != ERROR_SUCCESS)
2174 return r;
2176 if (!swap)
2177 continue;
2179 ERR("Bad order! %d\n", i);
2180 return ERROR_FUNCTION_FAILED;
2183 return ERROR_SUCCESS;
2186 static UINT TABLE_sort(struct tagMSIVIEW *view, column_info *columns)
2188 MSITABLEVIEW *tv = (MSITABLEVIEW *)view;
2189 MSIORDERINFO *order;
2190 column_info *ptr;
2191 UINT r, i;
2192 UINT rows, cols;
2194 TRACE("sorting table %s\n", debugstr_w(tv->name));
2196 r = TABLE_get_dimensions(view, &rows, &cols);
2197 if (r != ERROR_SUCCESS)
2198 return r;
2200 if (rows == 0)
2201 return ERROR_SUCCESS;
2203 order = msi_alloc_zero(sizeof(MSIORDERINFO) + sizeof(UINT) * cols);
2204 if (!order)
2205 return ERROR_OUTOFMEMORY;
2207 for (ptr = columns; ptr; ptr = ptr->next)
2208 order_add_column(view, order, ptr->column);
2210 order->reorder = msi_alloc(rows * sizeof(UINT));
2211 if (!order->reorder)
2212 return ERROR_OUTOFMEMORY;
2214 for (i = 0; i < rows; i++)
2215 order->reorder[i] = i;
2217 r = order_mergesort(view, order, 0, rows - 1);
2218 if (r != ERROR_SUCCESS)
2219 return r;
2221 r = order_verify(view, order, rows);
2222 if (r != ERROR_SUCCESS)
2223 return r;
2225 tv->order = order;
2227 return ERROR_SUCCESS;
2230 static UINT TABLE_drop(struct tagMSIVIEW *view)
2232 MSITABLEVIEW *tv = (MSITABLEVIEW*)view;
2233 MSIVIEW *tables = NULL;
2234 MSIRECORD *rec = NULL;
2235 UINT r, row;
2236 INT i;
2238 TRACE("dropping table %s\n", debugstr_w(tv->name));
2240 for (i = tv->table->col_count - 1; i >= 0; i--)
2242 r = TABLE_remove_column(view, tv->table->colinfo[i].tablename,
2243 tv->table->colinfo[i].number);
2244 if (r != ERROR_SUCCESS)
2245 return r;
2248 rec = MSI_CreateRecord(1);
2249 if (!rec)
2250 return ERROR_OUTOFMEMORY;
2252 MSI_RecordSetStringW(rec, 1, tv->name);
2254 r = TABLE_CreateView(tv->db, szTables, &tables);
2255 if (r != ERROR_SUCCESS)
2256 return r;
2258 r = msi_table_find_row((MSITABLEVIEW *)tables, rec, &row, NULL);
2259 if (r != ERROR_SUCCESS)
2260 goto done;
2262 r = TABLE_delete_row(tables, row);
2263 if (r != ERROR_SUCCESS)
2264 goto done;
2266 list_remove(&tv->table->entry);
2267 free_table(tv->table);
2269 done:
2270 msiobj_release(&rec->hdr);
2271 tables->ops->delete(tables);
2273 return r;
2276 static const MSIVIEWOPS table_ops =
2278 TABLE_fetch_int,
2279 TABLE_fetch_stream,
2280 TABLE_get_row,
2281 TABLE_set_row,
2282 TABLE_insert_row,
2283 TABLE_delete_row,
2284 TABLE_execute,
2285 TABLE_close,
2286 TABLE_get_dimensions,
2287 TABLE_get_column_info,
2288 TABLE_modify,
2289 TABLE_delete,
2290 TABLE_find_matching_rows,
2291 TABLE_add_ref,
2292 TABLE_release,
2293 TABLE_add_column,
2294 TABLE_remove_column,
2295 TABLE_sort,
2296 TABLE_drop,
2299 UINT TABLE_CreateView( MSIDATABASE *db, LPCWSTR name, MSIVIEW **view )
2301 MSITABLEVIEW *tv ;
2302 UINT r, sz;
2304 TRACE("%p %s %p\n", db, debugstr_w(name), view );
2306 if ( !strcmpW( name, szStreams ) )
2307 return STREAMS_CreateView( db, view );
2308 else if ( !strcmpW( name, szStorages ) )
2309 return STORAGES_CreateView( db, view );
2311 sz = sizeof *tv + lstrlenW(name)*sizeof name[0] ;
2312 tv = msi_alloc_zero( sz );
2313 if( !tv )
2314 return ERROR_FUNCTION_FAILED;
2316 r = get_table( db, name, &tv->table );
2317 if( r != ERROR_SUCCESS )
2319 msi_free( tv );
2320 WARN("table not found\n");
2321 return r;
2324 TRACE("table %p found with %d columns\n", tv->table, tv->table->col_count);
2326 /* fill the structure */
2327 tv->view.ops = &table_ops;
2328 tv->db = db;
2329 tv->columns = tv->table->colinfo;
2330 tv->num_cols = tv->table->col_count;
2331 tv->row_size = msi_table_get_row_size( db, tv->table->colinfo, tv->table->col_count, LONG_STR_BYTES );
2333 TRACE("%s one row is %d bytes\n", debugstr_w(name), tv->row_size );
2335 *view = (MSIVIEW*) tv;
2336 lstrcpyW( tv->name, name );
2338 return ERROR_SUCCESS;
2341 UINT MSI_CommitTables( MSIDATABASE *db )
2343 UINT r, bytes_per_strref;
2344 HRESULT hr;
2345 MSITABLE *table = NULL;
2347 TRACE("%p\n",db);
2349 r = msi_save_string_table( db->strings, db->storage, &bytes_per_strref );
2350 if( r != ERROR_SUCCESS )
2352 WARN("failed to save string table r=%08x\n",r);
2353 return r;
2356 LIST_FOR_EACH_ENTRY( table, &db->tables, MSITABLE, entry )
2358 r = save_table( db, table, bytes_per_strref );
2359 if( r != ERROR_SUCCESS )
2361 WARN("failed to save table %s (r=%08x)\n",
2362 debugstr_w(table->name), r);
2363 return r;
2367 /* force everything to reload next time */
2368 free_cached_tables( db );
2370 hr = IStorage_Commit( db->storage, 0 );
2371 if (FAILED( hr ))
2373 WARN("failed to commit changes 0x%08x\n", hr);
2374 r = ERROR_FUNCTION_FAILED;
2376 return r;
2379 MSICONDITION MSI_DatabaseIsTablePersistent( MSIDATABASE *db, LPCWSTR table )
2381 MSITABLE *t;
2382 UINT r;
2384 TRACE("%p %s\n", db, debugstr_w(table));
2386 if (!table)
2387 return MSICONDITION_ERROR;
2389 r = get_table( db, table, &t );
2390 if (r != ERROR_SUCCESS)
2391 return MSICONDITION_NONE;
2393 return t->persistent;
2396 static UINT read_raw_int(const BYTE *data, UINT col, UINT bytes)
2398 UINT ret = 0, i;
2400 for (i = 0; i < bytes; i++)
2401 ret += (data[col + i] << i * 8);
2403 return ret;
2406 static UINT msi_record_encoded_stream_name( const MSITABLEVIEW *tv, MSIRECORD *rec, LPWSTR *pstname )
2408 LPWSTR stname = NULL, sval, p;
2409 DWORD len;
2410 UINT i, r;
2412 TRACE("%p %p\n", tv, rec);
2414 len = lstrlenW( tv->name ) + 1;
2415 stname = msi_alloc( len*sizeof(WCHAR) );
2416 if ( !stname )
2418 r = ERROR_OUTOFMEMORY;
2419 goto err;
2422 lstrcpyW( stname, tv->name );
2424 for ( i = 0; i < tv->num_cols; i++ )
2426 if ( tv->columns[i].type & MSITYPE_KEY )
2428 sval = msi_dup_record_field( rec, i + 1 );
2429 if ( !sval )
2431 r = ERROR_OUTOFMEMORY;
2432 goto err;
2435 len += lstrlenW( szDot ) + lstrlenW ( sval );
2436 p = msi_realloc ( stname, len*sizeof(WCHAR) );
2437 if ( !p )
2439 r = ERROR_OUTOFMEMORY;
2440 goto err;
2442 stname = p;
2444 lstrcatW( stname, szDot );
2445 lstrcatW( stname, sval );
2447 msi_free( sval );
2449 else
2450 continue;
2453 *pstname = encode_streamname( FALSE, stname );
2454 msi_free( stname );
2456 return ERROR_SUCCESS;
2458 err:
2459 msi_free ( stname );
2460 *pstname = NULL;
2461 return r;
2464 static MSIRECORD *msi_get_transform_record( const MSITABLEVIEW *tv, const string_table *st,
2465 IStorage *stg,
2466 const BYTE *rawdata, UINT bytes_per_strref )
2468 UINT i, val, ofs = 0;
2469 USHORT mask;
2470 MSICOLUMNINFO *columns = tv->columns;
2471 MSIRECORD *rec;
2473 mask = rawdata[0] | (rawdata[1] << 8);
2474 rawdata += 2;
2476 rec = MSI_CreateRecord( tv->num_cols );
2477 if( !rec )
2478 return rec;
2480 TRACE("row ->\n");
2481 for( i=0; i<tv->num_cols; i++ )
2483 if ( (mask&1) && (i>=(mask>>8)) )
2484 break;
2485 /* all keys must be present */
2486 if ( (~mask&1) && (~columns[i].type & MSITYPE_KEY) && ((1<<i) & ~mask) )
2487 continue;
2489 if( MSITYPE_IS_BINARY(tv->columns[i].type) )
2491 LPWSTR encname;
2492 IStream *stm = NULL;
2493 UINT r;
2495 ofs += bytes_per_column( tv->db, &columns[i], bytes_per_strref );
2497 r = msi_record_encoded_stream_name( tv, rec, &encname );
2498 if ( r != ERROR_SUCCESS )
2499 return NULL;
2501 r = IStorage_OpenStream( stg, encname, NULL,
2502 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &stm );
2503 msi_free( encname );
2504 if ( r != ERROR_SUCCESS )
2505 return NULL;
2507 MSI_RecordSetStream( rec, i+1, stm );
2508 TRACE(" field %d [%s]\n", i+1, debugstr_w(encname));
2510 else if( columns[i].type & MSITYPE_STRING )
2512 LPCWSTR sval;
2514 val = read_raw_int(rawdata, ofs, bytes_per_strref);
2515 sval = msi_string_lookup_id( st, val );
2516 MSI_RecordSetStringW( rec, i+1, sval );
2517 TRACE(" field %d [%s]\n", i+1, debugstr_w(sval));
2518 ofs += bytes_per_strref;
2520 else
2522 UINT n = bytes_per_column( tv->db, &columns[i], bytes_per_strref );
2523 switch( n )
2525 case 2:
2526 val = read_raw_int(rawdata, ofs, n);
2527 if (val)
2528 MSI_RecordSetInteger( rec, i+1, val-0x8000 );
2529 TRACE(" field %d [0x%04x]\n", i+1, val );
2530 break;
2531 case 4:
2532 val = read_raw_int(rawdata, ofs, n);
2533 if (val)
2534 MSI_RecordSetInteger( rec, i+1, val^0x80000000 );
2535 TRACE(" field %d [0x%08x]\n", i+1, val );
2536 break;
2537 default:
2538 ERR("oops - unknown column width %d\n", n);
2539 break;
2541 ofs += n;
2544 return rec;
2547 static void dump_record( MSIRECORD *rec )
2549 UINT i, n;
2551 n = MSI_RecordGetFieldCount( rec );
2552 for( i=1; i<=n; i++ )
2554 LPCWSTR sval;
2556 if( MSI_RecordIsNull( rec, i ) )
2557 TRACE("row -> []\n");
2558 else if( (sval = MSI_RecordGetString( rec, i )) )
2559 TRACE("row -> [%s]\n", debugstr_w(sval));
2560 else
2561 TRACE("row -> [0x%08x]\n", MSI_RecordGetInteger( rec, i ) );
2565 static void dump_table( const string_table *st, const USHORT *rawdata, UINT rawsize )
2567 LPCWSTR sval;
2568 UINT i;
2570 for( i=0; i<(rawsize/2); i++ )
2572 sval = msi_string_lookup_id( st, rawdata[i] );
2573 MESSAGE(" %04x %s\n", rawdata[i], debugstr_w(sval) );
2577 static UINT* msi_record_to_row( const MSITABLEVIEW *tv, MSIRECORD *rec )
2579 LPCWSTR str;
2580 UINT i, r, *data;
2582 data = msi_alloc( tv->num_cols *sizeof (UINT) );
2583 for( i=0; i<tv->num_cols; i++ )
2585 data[i] = 0;
2587 if ( ~tv->columns[i].type & MSITYPE_KEY )
2588 continue;
2590 /* turn the transform column value into a row value */
2591 if ( ( tv->columns[i].type & MSITYPE_STRING ) &&
2592 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2594 str = MSI_RecordGetString( rec, i+1 );
2595 if (str)
2597 r = msi_string2idW( tv->db->strings, str, &data[i] );
2599 /* if there's no matching string in the string table,
2600 these keys can't match any record, so fail now. */
2601 if (r != ERROR_SUCCESS)
2603 msi_free( data );
2604 return NULL;
2607 else data[i] = 0;
2609 else
2611 data[i] = MSI_RecordGetInteger( rec, i+1 );
2613 if (data[i] == MSI_NULL_INTEGER)
2614 data[i] = 0;
2615 else if ((tv->columns[i].type&0xff) == 2)
2616 data[i] += 0x8000;
2617 else
2618 data[i] += 0x80000000;
2621 return data;
2624 static UINT msi_row_matches( MSITABLEVIEW *tv, UINT row, const UINT *data, UINT *column )
2626 UINT i, r, x, ret = ERROR_FUNCTION_FAILED;
2628 for( i=0; i<tv->num_cols; i++ )
2630 if ( ~tv->columns[i].type & MSITYPE_KEY )
2631 continue;
2633 /* turn the transform column value into a row value */
2634 r = TABLE_fetch_int( &tv->view, row, i+1, &x );
2635 if ( r != ERROR_SUCCESS )
2637 ERR("TABLE_fetch_int shouldn't fail here\n");
2638 break;
2641 /* if this key matches, move to the next column */
2642 if ( x != data[i] )
2644 ret = ERROR_FUNCTION_FAILED;
2645 break;
2647 if (column) *column = i;
2648 ret = ERROR_SUCCESS;
2650 return ret;
2653 static UINT msi_table_find_row( MSITABLEVIEW *tv, MSIRECORD *rec, UINT *row, UINT *column )
2655 UINT i, r = ERROR_FUNCTION_FAILED, *data;
2657 data = msi_record_to_row( tv, rec );
2658 if( !data )
2659 return r;
2660 for( i = 0; i < tv->table->row_count; i++ )
2662 r = msi_row_matches( tv, i, data, column );
2663 if( r == ERROR_SUCCESS )
2665 *row = i;
2666 break;
2669 msi_free( data );
2670 return r;
2673 typedef struct
2675 struct list entry;
2676 LPWSTR name;
2677 } TRANSFORMDATA;
2679 static UINT msi_table_load_transform( MSIDATABASE *db, IStorage *stg,
2680 string_table *st, TRANSFORMDATA *transform,
2681 UINT bytes_per_strref )
2683 UINT rawsize = 0;
2684 BYTE *rawdata = NULL;
2685 MSITABLEVIEW *tv = NULL;
2686 UINT r, n, sz, i, mask;
2687 MSIRECORD *rec = NULL;
2688 UINT colcol = 0;
2689 WCHAR coltable[32];
2690 LPWSTR name;
2692 if (!transform)
2693 return ERROR_SUCCESS;
2695 name = transform->name;
2697 coltable[0] = 0;
2698 TRACE("%p %p %p %s\n", db, stg, st, debugstr_w(name) );
2700 /* read the transform data */
2701 read_stream_data( stg, name, TRUE, &rawdata, &rawsize );
2702 if ( !rawdata )
2704 TRACE("table %s empty\n", debugstr_w(name) );
2705 return ERROR_INVALID_TABLE;
2708 /* create a table view */
2709 r = TABLE_CreateView( db, name, (MSIVIEW**) &tv );
2710 if( r != ERROR_SUCCESS )
2711 goto err;
2713 r = tv->view.ops->execute( &tv->view, NULL );
2714 if( r != ERROR_SUCCESS )
2715 goto err;
2717 TRACE("name = %s columns = %u row_size = %u raw size = %u\n",
2718 debugstr_w(name), tv->num_cols, tv->row_size, rawsize );
2720 /* interpret the data */
2721 for( n=0; n < rawsize; )
2723 mask = rawdata[n] | (rawdata[n+1] << 8);
2725 if (mask&1)
2728 * if the low bit is set, columns are continuous and
2729 * the number of columns is specified in the high byte
2731 sz = 2;
2732 for( i=0; i<tv->num_cols; i++ )
2734 if( (tv->columns[i].type & MSITYPE_STRING) &&
2735 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2736 sz += bytes_per_strref;
2737 else
2738 sz += bytes_per_column( tv->db, &tv->columns[i], bytes_per_strref );
2741 else
2744 * If the low bit is not set, mask is a bitmask.
2745 * Excepting for key fields, which are always present,
2746 * each bit indicates that a field is present in the transform record.
2748 * mask == 0 is a special case ... only the keys will be present
2749 * and it means that this row should be deleted.
2751 sz = 2;
2752 for( i=0; i<tv->num_cols; i++ )
2754 if( (tv->columns[i].type & MSITYPE_KEY) || ((1<<i)&mask))
2756 if( (tv->columns[i].type & MSITYPE_STRING) &&
2757 ! MSITYPE_IS_BINARY(tv->columns[i].type) )
2758 sz += bytes_per_strref;
2759 else
2760 sz += bytes_per_column( tv->db, &tv->columns[i], bytes_per_strref );
2765 /* check we didn't run of the end of the table */
2766 if ( (n+sz) > rawsize )
2768 ERR("borked.\n");
2769 dump_table( st, (USHORT *)rawdata, rawsize );
2770 break;
2773 rec = msi_get_transform_record( tv, st, stg, &rawdata[n], bytes_per_strref );
2774 if (rec)
2776 WCHAR table[32];
2777 DWORD sz = 32;
2778 UINT number = MSI_NULL_INTEGER;
2779 UINT row = 0;
2781 if (!strcmpW( name, szColumns ))
2783 MSI_RecordGetStringW( rec, 1, table, &sz );
2784 number = MSI_RecordGetInteger( rec, 2 );
2787 * Native msi seems writes nul into the Number (2nd) column of
2788 * the _Columns table, only when the columns are from a new table
2790 if ( number == MSI_NULL_INTEGER )
2792 /* reset the column number on a new table */
2793 if (strcmpW( coltable, table ))
2795 colcol = 0;
2796 lstrcpyW( coltable, table );
2799 /* fix nul column numbers */
2800 MSI_RecordSetInteger( rec, 2, ++colcol );
2804 if (TRACE_ON(msidb)) dump_record( rec );
2806 r = msi_table_find_row( tv, rec, &row, NULL );
2807 if (r == ERROR_SUCCESS)
2809 if (!mask)
2811 TRACE("deleting row [%d]:\n", row);
2812 r = TABLE_delete_row( &tv->view, row );
2813 if (r != ERROR_SUCCESS)
2814 WARN("failed to delete row %u\n", r);
2816 else if (mask & 1)
2818 TRACE("modifying full row [%d]:\n", row);
2819 r = TABLE_set_row( &tv->view, row, rec, (1 << tv->num_cols) - 1 );
2820 if (r != ERROR_SUCCESS)
2821 WARN("failed to modify row %u\n", r);
2823 else
2825 TRACE("modifying masked row [%d]:\n", row);
2826 r = TABLE_set_row( &tv->view, row, rec, mask );
2827 if (r != ERROR_SUCCESS)
2828 WARN("failed to modify row %u\n", r);
2831 else
2833 TRACE("inserting row\n");
2834 r = TABLE_insert_row( &tv->view, rec, -1, FALSE );
2835 if (r != ERROR_SUCCESS)
2836 WARN("failed to insert row %u\n", r);
2839 if (number != MSI_NULL_INTEGER && !strcmpW( name, szColumns ))
2840 msi_update_table_columns( db, table );
2842 msiobj_release( &rec->hdr );
2845 n += sz;
2848 err:
2849 /* no need to free the table, it's associated with the database */
2850 msi_free( rawdata );
2851 if( tv )
2852 tv->view.ops->delete( &tv->view );
2854 return ERROR_SUCCESS;
2858 * msi_table_apply_transform
2860 * Enumerate the table transforms in a transform storage and apply each one.
2862 UINT msi_table_apply_transform( MSIDATABASE *db, IStorage *stg )
2864 struct list transforms;
2865 IEnumSTATSTG *stgenum = NULL;
2866 TRANSFORMDATA *transform;
2867 TRANSFORMDATA *tables = NULL, *columns = NULL;
2868 HRESULT r;
2869 STATSTG stat;
2870 string_table *strings;
2871 UINT ret = ERROR_FUNCTION_FAILED;
2872 UINT bytes_per_strref;
2874 TRACE("%p %p\n", db, stg );
2876 strings = msi_load_string_table( stg, &bytes_per_strref );
2877 if( !strings )
2878 goto end;
2880 r = IStorage_EnumElements( stg, 0, NULL, 0, &stgenum );
2881 if( FAILED( r ) )
2882 goto end;
2884 list_init(&transforms);
2886 while ( TRUE )
2888 MSITABLEVIEW *tv = NULL;
2889 WCHAR name[0x40];
2890 ULONG count = 0;
2892 r = IEnumSTATSTG_Next( stgenum, 1, &stat, &count );
2893 if ( FAILED( r ) || !count )
2894 break;
2896 decode_streamname( stat.pwcsName, name );
2897 CoTaskMemFree( stat.pwcsName );
2898 if ( name[0] != 0x4840 )
2899 continue;
2901 if ( !strcmpW( name+1, szStringPool ) ||
2902 !strcmpW( name+1, szStringData ) )
2903 continue;
2905 transform = msi_alloc_zero( sizeof(TRANSFORMDATA) );
2906 if ( !transform )
2907 break;
2909 list_add_tail( &transforms, &transform->entry );
2911 transform->name = strdupW( name + 1 );
2913 if ( !strcmpW( transform->name, szTables ) )
2914 tables = transform;
2915 else if (!strcmpW( transform->name, szColumns ) )
2916 columns = transform;
2918 TRACE("transform contains stream %s\n", debugstr_w(name));
2920 /* load the table */
2921 r = TABLE_CreateView( db, transform->name, (MSIVIEW**) &tv );
2922 if( r != ERROR_SUCCESS )
2923 continue;
2925 r = tv->view.ops->execute( &tv->view, NULL );
2926 if( r != ERROR_SUCCESS )
2928 tv->view.ops->delete( &tv->view );
2929 continue;
2932 tv->view.ops->delete( &tv->view );
2936 * Apply _Tables and _Columns transforms first so that
2937 * the table metadata is correct, and empty tables exist.
2939 ret = msi_table_load_transform( db, stg, strings, tables, bytes_per_strref );
2940 if (ret != ERROR_SUCCESS && ret != ERROR_INVALID_TABLE)
2941 goto end;
2943 ret = msi_table_load_transform( db, stg, strings, columns, bytes_per_strref );
2944 if (ret != ERROR_SUCCESS && ret != ERROR_INVALID_TABLE)
2945 goto end;
2947 ret = ERROR_SUCCESS;
2949 while ( !list_empty( &transforms ) )
2951 transform = LIST_ENTRY( list_head( &transforms ), TRANSFORMDATA, entry );
2953 if ( strcmpW( transform->name, szColumns ) &&
2954 strcmpW( transform->name, szTables ) &&
2955 ret == ERROR_SUCCESS )
2957 ret = msi_table_load_transform( db, stg, strings, transform, bytes_per_strref );
2960 list_remove( &transform->entry );
2961 msi_free( transform->name );
2962 msi_free( transform );
2965 if ( ret == ERROR_SUCCESS )
2966 append_storage_to_db( db, stg );
2968 end:
2969 if ( stgenum )
2970 IEnumSTATSTG_Release( stgenum );
2971 if ( strings )
2972 msi_destroy_stringtable( strings );
2974 return ret;