-sync msi with wine 1.1.32
[reactos.git] / reactos / dll / win32 / msi / database.c
1 /*
2 * Implementation of the Microsoft Installer (msi.dll)
3 *
4 * Copyright 2002,2003,2004,2005 Mike McCormack for CodeWeavers
5 *
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.
10 *
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.
15 *
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
19 */
20
21 #include <stdarg.h>
22
23 #define COBJMACROS
24 #define NONAMELESSUNION
25
26 #include "windef.h"
27 #include "winbase.h"
28 #include "winreg.h"
29 #include "winnls.h"
30 #include "wine/debug.h"
31 #include "wine/unicode.h"
32 #include "msi.h"
33 #include "msiquery.h"
34 #include "msipriv.h"
35 #include "objidl.h"
36 #include "objbase.h"
37 #include "msiserver.h"
38 #include "query.h"
39
40 #include "initguid.h"
41
42 WINE_DEFAULT_DEBUG_CHANNEL(msi);
43
44 /*
45 * .MSI file format
46 *
47 * An .msi file is a structured storage file.
48 * It contains a number of streams.
49 * A stream for each table in the database.
50 * Two streams for the string table in the database.
51 * Any binary data in a table is a reference to a stream.
52 */
53
54 static VOID MSI_CloseDatabase( MSIOBJECTHDR *arg )
55 {
56 MSIDATABASE *db = (MSIDATABASE *) arg;
57
58 msi_free(db->path);
59 free_cached_tables( db );
60 msi_free_transforms( db );
61 msi_destroy_stringtable( db->strings );
62 IStorage_Release( db->storage );
63 if (db->deletefile)
64 {
65 DeleteFileW( db->deletefile );
66 msi_free( db->deletefile );
67 }
68 if (db->localfile)
69 {
70 DeleteFileW( db->localfile );
71 msi_free( db->localfile );
72 }
73 }
74
75 UINT MSI_OpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIDATABASE **pdb)
76 {
77 IStorage *stg = NULL;
78 HRESULT r;
79 MSIDATABASE *db = NULL;
80 UINT ret = ERROR_FUNCTION_FAILED;
81 LPCWSTR szMode, save_path;
82 STATSTG stat;
83 BOOL created = FALSE;
84 WCHAR path[MAX_PATH];
85
86 static const WCHAR szTables[] = { '_','T','a','b','l','e','s',0 };
87
88 TRACE("%s %s\n",debugstr_w(szDBPath),debugstr_w(szPersist) );
89
90 if( !pdb )
91 return ERROR_INVALID_PARAMETER;
92
93 if (szPersist - MSIDBOPEN_PATCHFILE >= MSIDBOPEN_READONLY &&
94 szPersist - MSIDBOPEN_PATCHFILE <= MSIDBOPEN_CREATEDIRECT)
95 {
96 TRACE("Database is a patch\n");
97 szPersist -= MSIDBOPEN_PATCHFILE;
98 }
99
100 save_path = szDBPath;
101 szMode = szPersist;
102 if( HIWORD( szPersist ) )
103 {
104 if (!CopyFileW( szDBPath, szPersist, FALSE ))
105 return ERROR_OPEN_FAILED;
106
107 szDBPath = szPersist;
108 szPersist = MSIDBOPEN_TRANSACT;
109 created = TRUE;
110 }
111
112 if( szPersist == MSIDBOPEN_READONLY )
113 {
114 r = StgOpenStorage( szDBPath, NULL,
115 STGM_DIRECT|STGM_READ|STGM_SHARE_DENY_WRITE, NULL, 0, &stg);
116 }
117 else if( szPersist == MSIDBOPEN_CREATE || szPersist == MSIDBOPEN_CREATEDIRECT )
118 {
119 /* FIXME: MSIDBOPEN_CREATE should case STGM_TRANSACTED flag to be
120 * used here: */
121 r = StgCreateDocfile( szDBPath,
122 STGM_CREATE|STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, 0, &stg);
123 if( r == ERROR_SUCCESS )
124 {
125 IStorage_SetClass( stg, &CLSID_MsiDatabase );
126 /* create the _Tables stream */
127 r = write_stream_data(stg, szTables, NULL, 0, TRUE);
128 if (SUCCEEDED(r))
129 r = msi_init_string_table( stg );
130 }
131 created = TRUE;
132 }
133 else if( szPersist == MSIDBOPEN_TRANSACT )
134 {
135 /* FIXME: MSIDBOPEN_TRANSACT should case STGM_TRANSACTED flag to be
136 * used here: */
137 r = StgOpenStorage( szDBPath, NULL,
138 STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, NULL, 0, &stg);
139 }
140 else if( szPersist == MSIDBOPEN_DIRECT )
141 {
142 r = StgOpenStorage( szDBPath, NULL,
143 STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, NULL, 0, &stg);
144 }
145 else
146 {
147 ERR("unknown flag %p\n",szPersist);
148 return ERROR_INVALID_PARAMETER;
149 }
150
151 if( FAILED( r ) || !stg )
152 {
153 FIXME("open failed r = %08x for %s\n", r, debugstr_w(szDBPath));
154 return ERROR_FUNCTION_FAILED;
155 }
156
157 r = IStorage_Stat( stg, &stat, STATFLAG_NONAME );
158 if( FAILED( r ) )
159 {
160 FIXME("Failed to stat storage\n");
161 goto end;
162 }
163
164 if ( !IsEqualGUID( &stat.clsid, &CLSID_MsiDatabase ) &&
165 !IsEqualGUID( &stat.clsid, &CLSID_MsiPatch ) &&
166 !IsEqualGUID( &stat.clsid, &CLSID_MsiTransform ) )
167 {
168 ERR("storage GUID is not a MSI database GUID %s\n",
169 debugstr_guid(&stat.clsid) );
170 goto end;
171 }
172
173 db = alloc_msiobject( MSIHANDLETYPE_DATABASE, sizeof (MSIDATABASE),
174 MSI_CloseDatabase );
175 if( !db )
176 {
177 FIXME("Failed to allocate a handle\n");
178 goto end;
179 }
180
181 if (!strchrW( save_path, '\\' ))
182 {
183 GetCurrentDirectoryW( MAX_PATH, path );
184 lstrcatW( path, szBackSlash );
185 lstrcatW( path, save_path );
186 }
187 else
188 lstrcpyW( path, save_path );
189
190 db->path = strdupW( path );
191
192 if( TRACE_ON( msi ) )
193 enum_stream_names( stg );
194
195 db->storage = stg;
196 db->mode = szMode;
197 if (created)
198 db->deletefile = strdupW( szDBPath );
199 list_init( &db->tables );
200 list_init( &db->transforms );
201
202 db->strings = msi_load_string_table( stg, &db->bytes_per_strref );
203 if( !db->strings )
204 goto end;
205
206 ret = ERROR_SUCCESS;
207
208 msiobj_addref( &db->hdr );
209 IStorage_AddRef( stg );
210 *pdb = db;
211
212 end:
213 if( db )
214 msiobj_release( &db->hdr );
215 if( stg )
216 IStorage_Release( stg );
217
218 return ret;
219 }
220
221 UINT WINAPI MsiOpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIHANDLE *phDB)
222 {
223 MSIDATABASE *db;
224 UINT ret;
225
226 TRACE("%s %s %p\n",debugstr_w(szDBPath),debugstr_w(szPersist), phDB);
227
228 ret = MSI_OpenDatabaseW( szDBPath, szPersist, &db );
229 if( ret == ERROR_SUCCESS )
230 {
231 *phDB = alloc_msihandle( &db->hdr );
232 if (! *phDB)
233 ret = ERROR_NOT_ENOUGH_MEMORY;
234 msiobj_release( &db->hdr );
235 }
236
237 return ret;
238 }
239
240 UINT WINAPI MsiOpenDatabaseA(LPCSTR szDBPath, LPCSTR szPersist, MSIHANDLE *phDB)
241 {
242 HRESULT r = ERROR_FUNCTION_FAILED;
243 LPWSTR szwDBPath = NULL, szwPersist = NULL;
244
245 TRACE("%s %s %p\n", debugstr_a(szDBPath), debugstr_a(szPersist), phDB);
246
247 if( szDBPath )
248 {
249 szwDBPath = strdupAtoW( szDBPath );
250 if( !szwDBPath )
251 goto end;
252 }
253
254 if( HIWORD(szPersist) )
255 {
256 szwPersist = strdupAtoW( szPersist );
257 if( !szwPersist )
258 goto end;
259 }
260 else
261 szwPersist = (LPWSTR)(DWORD_PTR)szPersist;
262
263 r = MsiOpenDatabaseW( szwDBPath, szwPersist, phDB );
264
265 end:
266 if( HIWORD(szPersist) )
267 msi_free( szwPersist );
268 msi_free( szwDBPath );
269
270 return r;
271 }
272
273 static LPWSTR msi_read_text_archive(LPCWSTR path)
274 {
275 HANDLE file;
276 LPSTR data = NULL;
277 LPWSTR wdata = NULL;
278 DWORD read, size = 0;
279
280 file = CreateFileW( path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );
281 if (file == INVALID_HANDLE_VALUE)
282 return NULL;
283
284 size = GetFileSize( file, NULL );
285 data = msi_alloc( size + 1 );
286 if (!data)
287 goto done;
288
289 if (!ReadFile( file, data, size, &read, NULL ))
290 goto done;
291
292 data[size] = '\0';
293 wdata = strdupAtoW( data );
294
295 done:
296 CloseHandle( file );
297 msi_free( data );
298 return wdata;
299 }
300
301 static void msi_parse_line(LPWSTR *line, LPWSTR **entries, DWORD *num_entries)
302 {
303 LPWSTR ptr = *line, save;
304 DWORD i, count = 1;
305
306 *entries = NULL;
307
308 /* stay on this line */
309 while (*ptr && *ptr != '\n')
310 {
311 /* entries are separated by tabs */
312 if (*ptr == '\t')
313 count++;
314
315 ptr++;
316 }
317
318 *entries = msi_alloc(count * sizeof(LPWSTR));
319 if (!*entries)
320 return;
321
322 /* store pointers into the data */
323 for (i = 0, ptr = *line; i < count; i++)
324 {
325 while (*ptr && *ptr == '\r') ptr++;
326 save = ptr;
327
328 while (*ptr && *ptr != '\t' && *ptr != '\n' && *ptr != '\r') ptr++;
329
330 /* NULL-separate the data */
331 if (*ptr == '\n' || *ptr == '\r')
332 {
333 while (*ptr == '\n' || *ptr == '\r')
334 *(ptr++) = '\0';
335 }
336 else if (*ptr)
337 *ptr++ = '\0';
338
339 (*entries)[i] = save;
340 }
341
342 /* move to the next line if there's more, else EOF */
343 *line = ptr;
344
345 if (num_entries)
346 *num_entries = count;
347 }
348
349 static LPWSTR msi_build_createsql_prelude(LPWSTR table)
350 {
351 LPWSTR prelude;
352 DWORD size;
353
354 static const WCHAR create_fmt[] = {'C','R','E','A','T','E',' ','T','A','B','L','E',' ','`','%','s','`',' ','(',' ',0};
355
356 size = sizeof(create_fmt)/sizeof(create_fmt[0]) + lstrlenW(table) - 2;
357 prelude = msi_alloc(size * sizeof(WCHAR));
358 if (!prelude)
359 return NULL;
360
361 sprintfW(prelude, create_fmt, table);
362 return prelude;
363 }
364
365 static LPWSTR msi_build_createsql_columns(LPWSTR *columns_data, LPWSTR *types, DWORD num_columns)
366 {
367 LPWSTR columns, p;
368 LPCWSTR type;
369 DWORD sql_size = 1, i, len;
370 WCHAR expanded[128], *ptr;
371 WCHAR size[10], comma[2], extra[30];
372
373 static const WCHAR column_fmt[] = {'`','%','s','`',' ','%','s','%','s','%','s','%','s',' ',0};
374 static const WCHAR size_fmt[] = {'(','%','s',')',0};
375 static const WCHAR type_char[] = {'C','H','A','R',0};
376 static const WCHAR type_int[] = {'I','N','T',0};
377 static const WCHAR type_long[] = {'L','O','N','G',0};
378 static const WCHAR type_object[] = {'O','B','J','E','C','T',0};
379 static const WCHAR type_notnull[] = {' ','N','O','T',' ','N','U','L','L',0};
380 static const WCHAR localizable[] = {' ','L','O','C','A','L','I','Z','A','B','L','E',0};
381
382 columns = msi_alloc_zero(sql_size * sizeof(WCHAR));
383 if (!columns)
384 return NULL;
385
386 for (i = 0; i < num_columns; i++)
387 {
388 type = NULL;
389 comma[1] = size[0] = extra[0] = '\0';
390
391 if (i == num_columns - 1)
392 comma[0] = '\0';
393 else
394 comma[0] = ',';
395
396 ptr = &types[i][1];
397 len = atolW(ptr);
398 extra[0] = '\0';
399
400 switch (types[i][0])
401 {
402 case 'l':
403 lstrcpyW(extra, type_notnull);
404 case 'L':
405 lstrcatW(extra, localizable);
406 type = type_char;
407 sprintfW(size, size_fmt, ptr);
408 break;
409 case 's':
410 lstrcpyW(extra, type_notnull);
411 case 'S':
412 type = type_char;
413 sprintfW(size, size_fmt, ptr);
414 break;
415 case 'i':
416 lstrcpyW(extra, type_notnull);
417 case 'I':
418 if (len <= 2)
419 type = type_int;
420 else if (len == 4)
421 type = type_long;
422 else
423 {
424 WARN("invalid int width %u\n", len);
425 msi_free(columns);
426 return NULL;
427 }
428 break;
429 case 'v':
430 lstrcpyW(extra, type_notnull);
431 case 'V':
432 type = type_object;
433 break;
434 default:
435 ERR("Unknown type: %c\n", types[i][0]);
436 msi_free(columns);
437 return NULL;
438 }
439
440 sprintfW(expanded, column_fmt, columns_data[i], type, size, extra, comma);
441 sql_size += lstrlenW(expanded);
442
443 p = msi_realloc(columns, sql_size * sizeof(WCHAR));
444 if (!p)
445 {
446 msi_free(columns);
447 return NULL;
448 }
449 columns = p;
450
451 lstrcatW(columns, expanded);
452 }
453
454 return columns;
455 }
456
457 static LPWSTR msi_build_createsql_postlude(LPWSTR *primary_keys, DWORD num_keys)
458 {
459 LPWSTR postlude, keys, ptr;
460 DWORD size, key_size, i;
461
462 static const WCHAR key_fmt[] = {'`','%','s','`',',',' ',0};
463 static const WCHAR postlude_fmt[] = {'P','R','I','M','A','R','Y',' ','K','E','Y',' ','%','s',')',0};
464
465 for (i = 0, size = 1; i < num_keys; i++)
466 size += lstrlenW(key_fmt) + lstrlenW(primary_keys[i]) - 2;
467
468 keys = msi_alloc(size * sizeof(WCHAR));
469 if (!keys)
470 return NULL;
471
472 for (i = 0, ptr = keys; i < num_keys; i++)
473 {
474 key_size = lstrlenW(key_fmt) + lstrlenW(primary_keys[i]) -2;
475 sprintfW(ptr, key_fmt, primary_keys[i]);
476 ptr += key_size;
477 }
478
479 /* remove final ', ' */
480 *(ptr - 2) = '\0';
481
482 size = lstrlenW(postlude_fmt) + size - 1;
483 postlude = msi_alloc(size * sizeof(WCHAR));
484 if (!postlude)
485 goto done;
486
487 sprintfW(postlude, postlude_fmt, keys);
488
489 done:
490 msi_free(keys);
491 return postlude;
492 }
493
494 static UINT msi_add_table_to_db(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types, LPWSTR *labels, DWORD num_labels, DWORD num_columns)
495 {
496 UINT r;
497 DWORD size;
498 MSIQUERY *view;
499 LPWSTR create_sql;
500 LPWSTR prelude, columns_sql, postlude;
501
502 prelude = msi_build_createsql_prelude(labels[0]);
503 columns_sql = msi_build_createsql_columns(columns, types, num_columns);
504 postlude = msi_build_createsql_postlude(labels + 1, num_labels - 1); /* skip over table name */
505
506 if (!prelude || !columns_sql || !postlude)
507 return ERROR_OUTOFMEMORY;
508
509 size = lstrlenW(prelude) + lstrlenW(columns_sql) + lstrlenW(postlude) + 1;
510 create_sql = msi_alloc(size * sizeof(WCHAR));
511 if (!create_sql)
512 return ERROR_OUTOFMEMORY;
513
514 lstrcpyW(create_sql, prelude);
515 lstrcatW(create_sql, columns_sql);
516 lstrcatW(create_sql, postlude);
517
518 msi_free(prelude);
519 msi_free(columns_sql);
520 msi_free(postlude);
521
522 r = MSI_DatabaseOpenViewW( db, create_sql, &view );
523 msi_free(create_sql);
524
525 if (r != ERROR_SUCCESS)
526 return r;
527
528 r = MSI_ViewExecute(view, NULL);
529 MSI_ViewClose(view);
530 msiobj_release(&view->hdr);
531
532 return r;
533 }
534
535 static LPWSTR msi_import_stream_filename(LPCWSTR path, LPCWSTR name)
536 {
537 DWORD len;
538 LPWSTR fullname, ptr;
539
540 len = lstrlenW(path) + lstrlenW(name) + 1;
541 fullname = msi_alloc(len*sizeof(WCHAR));
542 if (!fullname)
543 return NULL;
544
545 lstrcpyW( fullname, path );
546
547 /* chop off extension from path */
548 ptr = strrchrW(fullname, '.');
549 if (!ptr)
550 {
551 msi_free (fullname);
552 return NULL;
553 }
554 *ptr++ = '\\';
555 lstrcpyW( ptr, name );
556 return fullname;
557 }
558
559 static UINT construct_record(DWORD num_columns, LPWSTR *types,
560 LPWSTR *data, LPWSTR path, MSIRECORD **rec)
561 {
562 UINT i;
563
564 *rec = MSI_CreateRecord(num_columns);
565 if (!*rec)
566 return ERROR_OUTOFMEMORY;
567
568 for (i = 0; i < num_columns; i++)
569 {
570 switch (types[i][0])
571 {
572 case 'L': case 'l': case 'S': case 's':
573 MSI_RecordSetStringW(*rec, i + 1, data[i]);
574 break;
575 case 'I': case 'i':
576 if (*data[i])
577 MSI_RecordSetInteger(*rec, i + 1, atoiW(data[i]));
578 break;
579 case 'V': case 'v':
580 if (*data[i])
581 {
582 UINT r;
583 LPWSTR file = msi_import_stream_filename(path, data[i]);
584 if (!file)
585 return ERROR_FUNCTION_FAILED;
586
587 r = MSI_RecordSetStreamFromFileW(*rec, i + 1, file);
588 msi_free (file);
589 if (r != ERROR_SUCCESS)
590 return ERROR_FUNCTION_FAILED;
591 }
592 break;
593 default:
594 ERR("Unhandled column type: %c\n", types[i][0]);
595 msiobj_release(&(*rec)->hdr);
596 return ERROR_FUNCTION_FAILED;
597 }
598 }
599
600 return ERROR_SUCCESS;
601 }
602
603 static UINT msi_add_records_to_table(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types,
604 LPWSTR *labels, LPWSTR **records,
605 int num_columns, int num_records,
606 LPWSTR path)
607 {
608 UINT r;
609 int i;
610 MSIQUERY *view;
611 MSIRECORD *rec;
612
613 static const WCHAR select[] = {
614 'S','E','L','E','C','T',' ','*',' ',
615 'F','R','O','M',' ','`','%','s','`',0
616 };
617
618 r = MSI_OpenQuery(db, &view, select, labels[0]);
619 if (r != ERROR_SUCCESS)
620 return r;
621
622 while (MSI_ViewFetch(view, &rec) != ERROR_NO_MORE_ITEMS)
623 {
624 r = MSI_ViewModify(view, MSIMODIFY_DELETE, rec);
625 if (r != ERROR_SUCCESS)
626 goto done;
627 }
628
629 for (i = 0; i < num_records; i++)
630 {
631 r = construct_record(num_columns, types, records[i], path, &rec);
632 if (r != ERROR_SUCCESS)
633 goto done;
634
635 r = MSI_ViewModify(view, MSIMODIFY_INSERT, rec);
636 if (r != ERROR_SUCCESS)
637 {
638 msiobj_release(&rec->hdr);
639 goto done;
640 }
641
642 msiobj_release(&rec->hdr);
643 }
644
645 done:
646 msiobj_release(&view->hdr);
647 return r;
648 }
649
650 static UINT MSI_DatabaseImport(MSIDATABASE *db, LPCWSTR folder, LPCWSTR file)
651 {
652 UINT r;
653 DWORD len, i;
654 DWORD num_labels, num_types;
655 DWORD num_columns, num_records = 0;
656 LPWSTR *columns, *types, *labels;
657 LPWSTR path, ptr, data;
658 LPWSTR **records = NULL;
659 LPWSTR **temp_records;
660
661 static const WCHAR suminfo[] =
662 {'_','S','u','m','m','a','r','y','I','n','f','o','r','m','a','t','i','o','n',0};
663
664 TRACE("%p %s %s\n", db, debugstr_w(folder), debugstr_w(file) );
665
666 if( folder == NULL || file == NULL )
667 return ERROR_INVALID_PARAMETER;
668
669 len = lstrlenW(folder) + lstrlenW(szBackSlash) + lstrlenW(file) + 1;
670 path = msi_alloc( len * sizeof(WCHAR) );
671 if (!path)
672 return ERROR_OUTOFMEMORY;
673
674 lstrcpyW( path, folder );
675 lstrcatW( path, szBackSlash );
676 lstrcatW( path, file );
677
678 data = msi_read_text_archive( path );
679
680 ptr = data;
681 msi_parse_line( &ptr, &columns, &num_columns );
682 msi_parse_line( &ptr, &types, &num_types );
683 msi_parse_line( &ptr, &labels, &num_labels );
684
685 if (num_columns != num_types)
686 {
687 r = ERROR_FUNCTION_FAILED;
688 goto done;
689 }
690
691 records = msi_alloc(sizeof(LPWSTR *));
692 if (!records)
693 {
694 r = ERROR_OUTOFMEMORY;
695 goto done;
696 }
697
698 /* read in the table records */
699 while (*ptr)
700 {
701 msi_parse_line( &ptr, &records[num_records], NULL );
702
703 num_records++;
704 temp_records = msi_realloc(records, (num_records + 1) * sizeof(LPWSTR *));
705 if (!temp_records)
706 {
707 r = ERROR_OUTOFMEMORY;
708 goto done;
709 }
710 records = temp_records;
711 }
712
713 if (!strcmpW(labels[0], suminfo))
714 {
715 r = msi_add_suminfo( db, records, num_records, num_columns );
716 if (r != ERROR_SUCCESS)
717 {
718 r = ERROR_FUNCTION_FAILED;
719 goto done;
720 }
721 }
722 else
723 {
724 if (!TABLE_Exists(db, labels[0]))
725 {
726 r = msi_add_table_to_db( db, columns, types, labels, num_labels, num_columns );
727 if (r != ERROR_SUCCESS)
728 {
729 r = ERROR_FUNCTION_FAILED;
730 goto done;
731 }
732 }
733
734 r = msi_add_records_to_table( db, columns, types, labels, records, num_columns, num_records, path );
735 }
736
737 done:
738 msi_free(path);
739 msi_free(data);
740 msi_free(columns);
741 msi_free(types);
742 msi_free(labels);
743
744 for (i = 0; i < num_records; i++)
745 msi_free(records[i]);
746
747 msi_free(records);
748
749 return r;
750 }
751
752 UINT WINAPI MsiDatabaseImportW(MSIHANDLE handle, LPCWSTR szFolder, LPCWSTR szFilename)
753 {
754 MSIDATABASE *db;
755 UINT r;
756
757 TRACE("%x %s %s\n",handle,debugstr_w(szFolder), debugstr_w(szFilename));
758
759 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
760 if( !db )
761 {
762 IWineMsiRemoteDatabase *remote_database;
763
764 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
765 if ( !remote_database )
766 return ERROR_INVALID_HANDLE;
767
768 IWineMsiRemoteDatabase_Release( remote_database );
769 WARN("MsiDatabaseImport not allowed during a custom action!\n");
770
771 return ERROR_SUCCESS;
772 }
773
774 r = MSI_DatabaseImport( db, szFolder, szFilename );
775 msiobj_release( &db->hdr );
776 return r;
777 }
778
779 UINT WINAPI MsiDatabaseImportA( MSIHANDLE handle,
780 LPCSTR szFolder, LPCSTR szFilename )
781 {
782 LPWSTR path = NULL, file = NULL;
783 UINT r = ERROR_OUTOFMEMORY;
784
785 TRACE("%x %s %s\n", handle, debugstr_a(szFolder), debugstr_a(szFilename));
786
787 if( szFolder )
788 {
789 path = strdupAtoW( szFolder );
790 if( !path )
791 goto end;
792 }
793
794 if( szFilename )
795 {
796 file = strdupAtoW( szFilename );
797 if( !file )
798 goto end;
799 }
800
801 r = MsiDatabaseImportW( handle, path, file );
802
803 end:
804 msi_free( path );
805 msi_free( file );
806
807 return r;
808 }
809
810 static UINT msi_export_record( HANDLE handle, MSIRECORD *row, UINT start )
811 {
812 UINT i, count, len, r = ERROR_SUCCESS;
813 const char *sep;
814 char *buffer;
815 DWORD sz;
816
817 len = 0x100;
818 buffer = msi_alloc( len );
819 if ( !buffer )
820 return ERROR_OUTOFMEMORY;
821
822 count = MSI_RecordGetFieldCount( row );
823 for ( i=start; i<=count; i++ )
824 {
825 sz = len;
826 r = MSI_RecordGetStringA( row, i, buffer, &sz );
827 if (r == ERROR_MORE_DATA)
828 {
829 char *p = msi_realloc( buffer, sz + 1 );
830 if (!p)
831 break;
832 len = sz + 1;
833 buffer = p;
834 }
835 sz = len;
836 r = MSI_RecordGetStringA( row, i, buffer, &sz );
837 if (r != ERROR_SUCCESS)
838 break;
839
840 if (!WriteFile( handle, buffer, sz, &sz, NULL ))
841 {
842 r = ERROR_FUNCTION_FAILED;
843 break;
844 }
845
846 sep = (i < count) ? "\t" : "\r\n";
847 if (!WriteFile( handle, sep, strlen(sep), &sz, NULL ))
848 {
849 r = ERROR_FUNCTION_FAILED;
850 break;
851 }
852 }
853 msi_free( buffer );
854 return r;
855 }
856
857 static UINT msi_export_row( MSIRECORD *row, void *arg )
858 {
859 return msi_export_record( arg, row, 1 );
860 }
861
862 static UINT msi_export_forcecodepage( HANDLE handle )
863 {
864 DWORD sz;
865
866 static const char data[] = "\r\n\r\n0\t_ForceCodepage\r\n";
867
868 FIXME("Read the codepage from the strings table!\n");
869
870 sz = lstrlenA(data) + 1;
871 if (!WriteFile(handle, data, sz, &sz, NULL))
872 return ERROR_FUNCTION_FAILED;
873
874 return ERROR_SUCCESS;
875 }
876
877 static UINT MSI_DatabaseExport( MSIDATABASE *db, LPCWSTR table,
878 LPCWSTR folder, LPCWSTR file )
879 {
880 static const WCHAR query[] = {
881 's','e','l','e','c','t',' ','*',' ','f','r','o','m',' ','%','s',0 };
882 static const WCHAR forcecodepage[] = {
883 '_','F','o','r','c','e','C','o','d','e','p','a','g','e',0 };
884 MSIRECORD *rec = NULL;
885 MSIQUERY *view = NULL;
886 LPWSTR filename;
887 HANDLE handle;
888 UINT len, r;
889
890 TRACE("%p %s %s %s\n", db, debugstr_w(table),
891 debugstr_w(folder), debugstr_w(file) );
892
893 if( folder == NULL || file == NULL )
894 return ERROR_INVALID_PARAMETER;
895
896 len = lstrlenW(folder) + lstrlenW(file) + 2;
897 filename = msi_alloc(len * sizeof (WCHAR));
898 if (!filename)
899 return ERROR_OUTOFMEMORY;
900
901 lstrcpyW( filename, folder );
902 lstrcatW( filename, szBackSlash );
903 lstrcatW( filename, file );
904
905 handle = CreateFileW( filename, GENERIC_READ | GENERIC_WRITE, 0,
906 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
907 msi_free( filename );
908 if (handle == INVALID_HANDLE_VALUE)
909 return ERROR_FUNCTION_FAILED;
910
911 if (!lstrcmpW( table, forcecodepage ))
912 {
913 r = msi_export_forcecodepage( handle );
914 goto done;
915 }
916
917 r = MSI_OpenQuery( db, &view, query, table );
918 if (r == ERROR_SUCCESS)
919 {
920 /* write out row 1, the column names */
921 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &rec);
922 if (r == ERROR_SUCCESS)
923 {
924 msi_export_record( handle, rec, 1 );
925 msiobj_release( &rec->hdr );
926 }
927
928 /* write out row 2, the column types */
929 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_TYPES, &rec);
930 if (r == ERROR_SUCCESS)
931 {
932 msi_export_record( handle, rec, 1 );
933 msiobj_release( &rec->hdr );
934 }
935
936 /* write out row 3, the table name + keys */
937 r = MSI_DatabaseGetPrimaryKeys( db, table, &rec );
938 if (r == ERROR_SUCCESS)
939 {
940 MSI_RecordSetStringW( rec, 0, table );
941 msi_export_record( handle, rec, 0 );
942 msiobj_release( &rec->hdr );
943 }
944
945 /* write out row 4 onwards, the data */
946 r = MSI_IterateRecords( view, 0, msi_export_row, handle );
947 msiobj_release( &view->hdr );
948 }
949
950 done:
951 CloseHandle( handle );
952 return r;
953 }
954
955 /***********************************************************************
956 * MsiExportDatabaseW [MSI.@]
957 *
958 * Writes a file containing the table data as tab separated ASCII.
959 *
960 * The format is as follows:
961 *
962 * row1 : colname1 <tab> colname2 <tab> .... colnameN <cr> <lf>
963 * row2 : coltype1 <tab> coltype2 <tab> .... coltypeN <cr> <lf>
964 * row3 : tablename <tab> key1 <tab> key2 <tab> ... keyM <cr> <lf>
965 *
966 * Followed by the data, starting at row 1 with one row per line
967 *
968 * row4 : data <tab> data <tab> data <tab> ... data <cr> <lf>
969 */
970 UINT WINAPI MsiDatabaseExportW( MSIHANDLE handle, LPCWSTR szTable,
971 LPCWSTR szFolder, LPCWSTR szFilename )
972 {
973 MSIDATABASE *db;
974 UINT r;
975
976 TRACE("%x %s %s %s\n", handle, debugstr_w(szTable),
977 debugstr_w(szFolder), debugstr_w(szFilename));
978
979 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
980 if( !db )
981 {
982 IWineMsiRemoteDatabase *remote_database;
983
984 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
985 if ( !remote_database )
986 return ERROR_INVALID_HANDLE;
987
988 IWineMsiRemoteDatabase_Release( remote_database );
989 WARN("MsiDatabaseExport not allowed during a custom action!\n");
990
991 return ERROR_SUCCESS;
992 }
993
994 r = MSI_DatabaseExport( db, szTable, szFolder, szFilename );
995 msiobj_release( &db->hdr );
996 return r;
997 }
998
999 UINT WINAPI MsiDatabaseExportA( MSIHANDLE handle, LPCSTR szTable,
1000 LPCSTR szFolder, LPCSTR szFilename )
1001 {
1002 LPWSTR path = NULL, file = NULL, table = NULL;
1003 UINT r = ERROR_OUTOFMEMORY;
1004
1005 TRACE("%x %s %s %s\n", handle, debugstr_a(szTable),
1006 debugstr_a(szFolder), debugstr_a(szFilename));
1007
1008 if( szTable )
1009 {
1010 table = strdupAtoW( szTable );
1011 if( !table )
1012 goto end;
1013 }
1014
1015 if( szFolder )
1016 {
1017 path = strdupAtoW( szFolder );
1018 if( !path )
1019 goto end;
1020 }
1021
1022 if( szFilename )
1023 {
1024 file = strdupAtoW( szFilename );
1025 if( !file )
1026 goto end;
1027 }
1028
1029 r = MsiDatabaseExportW( handle, table, path, file );
1030
1031 end:
1032 msi_free( table );
1033 msi_free( path );
1034 msi_free( file );
1035
1036 return r;
1037 }
1038
1039 UINT WINAPI MsiDatabaseMergeA(MSIHANDLE hDatabase, MSIHANDLE hDatabaseMerge,
1040 LPCSTR szTableName)
1041 {
1042 UINT r;
1043 LPWSTR table;
1044
1045 TRACE("(%d, %d, %s)\n", hDatabase, hDatabaseMerge,
1046 debugstr_a(szTableName));
1047
1048 table = strdupAtoW(szTableName);
1049 r = MsiDatabaseMergeW(hDatabase, hDatabaseMerge, table);
1050
1051 msi_free(table);
1052 return r;
1053 }
1054
1055 typedef struct _tagMERGETABLE
1056 {
1057 struct list entry;
1058 struct list rows;
1059 LPWSTR name;
1060 DWORD numconflicts;
1061 LPWSTR *columns;
1062 DWORD numcolumns;
1063 LPWSTR *types;
1064 DWORD numtypes;
1065 LPWSTR *labels;
1066 DWORD numlabels;
1067 } MERGETABLE;
1068
1069 typedef struct _tagMERGEROW
1070 {
1071 struct list entry;
1072 MSIRECORD *data;
1073 } MERGEROW;
1074
1075 typedef struct _tagMERGEDATA
1076 {
1077 MSIDATABASE *db;
1078 MSIDATABASE *merge;
1079 MERGETABLE *curtable;
1080 MSIQUERY *curview;
1081 struct list *tabledata;
1082 } MERGEDATA;
1083
1084 static BOOL merge_type_match(LPCWSTR type1, LPCWSTR type2)
1085 {
1086 if (((type1[0] == 'l') || (type1[0] == 's')) &&
1087 ((type2[0] == 'l') || (type2[0] == 's')))
1088 return TRUE;
1089
1090 if (((type1[0] == 'L') || (type1[0] == 'S')) &&
1091 ((type2[0] == 'L') || (type2[0] == 'S')))
1092 return TRUE;
1093
1094 return !lstrcmpW(type1, type2);
1095 }
1096
1097 static UINT merge_verify_colnames(MSIQUERY *dbview, MSIQUERY *mergeview)
1098 {
1099 MSIRECORD *dbrec, *mergerec;
1100 UINT r, i, count;
1101
1102 r = MSI_ViewGetColumnInfo(dbview, MSICOLINFO_NAMES, &dbrec);
1103 if (r != ERROR_SUCCESS)
1104 return r;
1105
1106 r = MSI_ViewGetColumnInfo(mergeview, MSICOLINFO_NAMES, &mergerec);
1107 if (r != ERROR_SUCCESS)
1108 return r;
1109
1110 count = MSI_RecordGetFieldCount(dbrec);
1111 for (i = 1; i <= count; i++)
1112 {
1113 if (!MSI_RecordGetString(mergerec, i))
1114 break;
1115
1116 if (lstrcmpW(MSI_RecordGetString(dbrec, i),
1117 MSI_RecordGetString(mergerec, i)))
1118 {
1119 r = ERROR_DATATYPE_MISMATCH;
1120 goto done;
1121 }
1122 }
1123
1124 msiobj_release(&dbrec->hdr);
1125 msiobj_release(&mergerec->hdr);
1126 dbrec = mergerec = NULL;
1127
1128 r = MSI_ViewGetColumnInfo(dbview, MSICOLINFO_TYPES, &dbrec);
1129 if (r != ERROR_SUCCESS)
1130 return r;
1131
1132 r = MSI_ViewGetColumnInfo(mergeview, MSICOLINFO_TYPES, &mergerec);
1133 if (r != ERROR_SUCCESS)
1134 return r;
1135
1136 count = MSI_RecordGetFieldCount(dbrec);
1137 for (i = 1; i <= count; i++)
1138 {
1139 if (!MSI_RecordGetString(mergerec, i))
1140 break;
1141
1142 if (!merge_type_match(MSI_RecordGetString(dbrec, i),
1143 MSI_RecordGetString(mergerec, i)))
1144 {
1145 r = ERROR_DATATYPE_MISMATCH;
1146 break;
1147 }
1148 }
1149
1150 done:
1151 msiobj_release(&dbrec->hdr);
1152 msiobj_release(&mergerec->hdr);
1153
1154 return r;
1155 }
1156
1157 static UINT merge_verify_primary_keys(MSIDATABASE *db, MSIDATABASE *mergedb,
1158 LPCWSTR table)
1159 {
1160 MSIRECORD *dbrec, *mergerec = NULL;
1161 UINT r, i, count;
1162
1163 r = MSI_DatabaseGetPrimaryKeys(db, table, &dbrec);
1164 if (r != ERROR_SUCCESS)
1165 return r;
1166
1167 r = MSI_DatabaseGetPrimaryKeys(mergedb, table, &mergerec);
1168 if (r != ERROR_SUCCESS)
1169 goto done;
1170
1171 count = MSI_RecordGetFieldCount(dbrec);
1172 if (count != MSI_RecordGetFieldCount(mergerec))
1173 {
1174 r = ERROR_DATATYPE_MISMATCH;
1175 goto done;
1176 }
1177
1178 for (i = 1; i <= count; i++)
1179 {
1180 if (lstrcmpW(MSI_RecordGetString(dbrec, i),
1181 MSI_RecordGetString(mergerec, i)))
1182 {
1183 r = ERROR_DATATYPE_MISMATCH;
1184 goto done;
1185 }
1186 }
1187
1188 done:
1189 msiobj_release(&dbrec->hdr);
1190 msiobj_release(&mergerec->hdr);
1191
1192 return r;
1193 }
1194
1195 static LPWSTR get_key_value(MSIQUERY *view, LPCWSTR key, MSIRECORD *rec)
1196 {
1197 MSIRECORD *colnames;
1198 LPWSTR str, val;
1199 UINT r, i = 0, sz = 0;
1200 int cmp;
1201
1202 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &colnames);
1203 if (r != ERROR_SUCCESS)
1204 return NULL;
1205
1206 do
1207 {
1208 str = msi_dup_record_field(colnames, ++i);
1209 cmp = lstrcmpW(key, str);
1210 msi_free(str);
1211 } while (cmp);
1212
1213 msiobj_release(&colnames->hdr);
1214
1215 r = MSI_RecordGetStringW(rec, i, NULL, &sz);
1216 if (r != ERROR_SUCCESS)
1217 return NULL;
1218 sz++;
1219
1220 if (MSI_RecordGetString(rec, i)) /* check record field is a string */
1221 {
1222 /* quote string record fields */
1223 const WCHAR szQuote[] = {'\'', 0};
1224 sz += 2;
1225 val = msi_alloc(sz*sizeof(WCHAR));
1226 if (!val)
1227 return NULL;
1228
1229 lstrcpyW(val, szQuote);
1230 r = MSI_RecordGetStringW(rec, i, val+1, &sz);
1231 lstrcpyW(val+1+sz, szQuote);
1232 }
1233 else
1234 {
1235 /* do not quote integer record fields */
1236 val = msi_alloc(sz*sizeof(WCHAR));
1237 if (!val)
1238 return NULL;
1239
1240 r = MSI_RecordGetStringW(rec, i, val, &sz);
1241 }
1242
1243 if (r != ERROR_SUCCESS)
1244 {
1245 ERR("failed to get string!\n");
1246 msi_free(val);
1247 return NULL;
1248 }
1249
1250 return val;
1251 }
1252
1253 static LPWSTR create_diff_row_query(MSIDATABASE *merge, MSIQUERY *view,
1254 LPWSTR table, MSIRECORD *rec)
1255 {
1256 LPWSTR query = NULL, clause = NULL;
1257 LPWSTR ptr = NULL, val;
1258 LPCWSTR setptr;
1259 DWORD size = 1, oldsize;
1260 LPCWSTR key;
1261 MSIRECORD *keys;
1262 UINT r, i, count;
1263
1264 static const WCHAR keyset[] = {
1265 '`','%','s','`',' ','=',' ','%','s',' ','A','N','D',' ',0};
1266 static const WCHAR lastkeyset[] = {
1267 '`','%','s','`',' ','=',' ','%','s',' ',0};
1268 static const WCHAR fmt[] = {'S','E','L','E','C','T',' ','*',' ',
1269 'F','R','O','M',' ','`','%','s','`',' ',
1270 'W','H','E','R','E',' ','%','s',0};
1271
1272 r = MSI_DatabaseGetPrimaryKeys(merge, table, &keys);
1273 if (r != ERROR_SUCCESS)
1274 return NULL;
1275
1276 clause = msi_alloc_zero(size * sizeof(WCHAR));
1277 if (!clause)
1278 goto done;
1279
1280 ptr = clause;
1281 count = MSI_RecordGetFieldCount(keys);
1282 for (i = 1; i <= count; i++)
1283 {
1284 key = MSI_RecordGetString(keys, i);
1285 val = get_key_value(view, key, rec);
1286
1287 if (i == count)
1288 setptr = lastkeyset;
1289 else
1290 setptr = keyset;
1291
1292 oldsize = size;
1293 size += lstrlenW(setptr) + lstrlenW(key) + lstrlenW(val) - 4;
1294 clause = msi_realloc(clause, size * sizeof (WCHAR));
1295 if (!clause)
1296 {
1297 msi_free(val);
1298 goto done;
1299 }
1300
1301 ptr = clause + oldsize - 1;
1302 sprintfW(ptr, setptr, key, val);
1303 msi_free(val);
1304 }
1305
1306 size = lstrlenW(fmt) + lstrlenW(table) + lstrlenW(clause) + 1;
1307 query = msi_alloc(size * sizeof(WCHAR));
1308 if (!query)
1309 goto done;
1310
1311 sprintfW(query, fmt, table, clause);
1312
1313 done:
1314 msi_free(clause);
1315 msiobj_release(&keys->hdr);
1316 return query;
1317 }
1318
1319 static UINT merge_diff_row(MSIRECORD *rec, LPVOID param)
1320 {
1321 MERGEDATA *data = param;
1322 MERGETABLE *table = data->curtable;
1323 MERGEROW *mergerow;
1324 MSIQUERY *dbview = NULL;
1325 MSIRECORD *row = NULL;
1326 LPWSTR query = NULL;
1327 UINT r = ERROR_SUCCESS;
1328
1329 if (TABLE_Exists(data->db, table->name))
1330 {
1331 query = create_diff_row_query(data->merge, data->curview, table->name, rec);
1332 if (!query)
1333 return ERROR_OUTOFMEMORY;
1334
1335 r = MSI_DatabaseOpenViewW(data->db, query, &dbview);
1336 if (r != ERROR_SUCCESS)
1337 goto done;
1338
1339 r = MSI_ViewExecute(dbview, NULL);
1340 if (r != ERROR_SUCCESS)
1341 goto done;
1342
1343 r = MSI_ViewFetch(dbview, &row);
1344 if (r == ERROR_SUCCESS && !MSI_RecordsAreEqual(rec, row))
1345 {
1346 table->numconflicts++;
1347 goto done;
1348 }
1349 else if (r != ERROR_NO_MORE_ITEMS)
1350 goto done;
1351
1352 r = ERROR_SUCCESS;
1353 }
1354
1355 mergerow = msi_alloc(sizeof(MERGEROW));
1356 if (!mergerow)
1357 {
1358 r = ERROR_OUTOFMEMORY;
1359 goto done;
1360 }
1361
1362 mergerow->data = MSI_CloneRecord(rec);
1363 if (!mergerow->data)
1364 {
1365 r = ERROR_OUTOFMEMORY;
1366 msi_free(mergerow);
1367 goto done;
1368 }
1369
1370 list_add_tail(&table->rows, &mergerow->entry);
1371
1372 done:
1373 msi_free(query);
1374 msiobj_release(&row->hdr);
1375 msiobj_release(&dbview->hdr);
1376 return r;
1377 }
1378
1379 static UINT msi_get_table_labels(MSIDATABASE *db, LPCWSTR table, LPWSTR **labels, DWORD *numlabels)
1380 {
1381 UINT r, i, count;
1382 MSIRECORD *prec = NULL;
1383
1384 r = MSI_DatabaseGetPrimaryKeys(db, table, &prec);
1385 if (r != ERROR_SUCCESS)
1386 return r;
1387
1388 count = MSI_RecordGetFieldCount(prec);
1389 *numlabels = count + 1;
1390 *labels = msi_alloc((*numlabels)*sizeof(LPWSTR));
1391 if (!*labels)
1392 {
1393 r = ERROR_OUTOFMEMORY;
1394 goto end;
1395 }
1396
1397 (*labels)[0] = strdupW(table);
1398 for (i=1; i<=count; i++ )
1399 {
1400 (*labels)[i] = strdupW(MSI_RecordGetString(prec, i));
1401 }
1402
1403 end:
1404 msiobj_release( &prec->hdr );
1405 return r;
1406 }
1407
1408 static UINT msi_get_query_columns(MSIQUERY *query, LPWSTR **columns, DWORD *numcolumns)
1409 {
1410 UINT r, i, count;
1411 MSIRECORD *prec = NULL;
1412
1413 r = MSI_ViewGetColumnInfo(query, MSICOLINFO_NAMES, &prec);
1414 if (r != ERROR_SUCCESS)
1415 return r;
1416
1417 count = MSI_RecordGetFieldCount(prec);
1418 *columns = msi_alloc(count*sizeof(LPWSTR));
1419 if (!*columns)
1420 {
1421 r = ERROR_OUTOFMEMORY;
1422 goto end;
1423 }
1424
1425 for (i=1; i<=count; i++ )
1426 {
1427 (*columns)[i-1] = strdupW(MSI_RecordGetString(prec, i));
1428 }
1429
1430 *numcolumns = count;
1431
1432 end:
1433 msiobj_release( &prec->hdr );
1434 return r;
1435 }
1436
1437 static UINT msi_get_query_types(MSIQUERY *query, LPWSTR **types, DWORD *numtypes)
1438 {
1439 UINT r, i, count;
1440 MSIRECORD *prec = NULL;
1441
1442 r = MSI_ViewGetColumnInfo(query, MSICOLINFO_TYPES, &prec);
1443 if (r != ERROR_SUCCESS)
1444 return r;
1445
1446 count = MSI_RecordGetFieldCount(prec);
1447 *types = msi_alloc(count*sizeof(LPWSTR));
1448 if (!*types)
1449 {
1450 r = ERROR_OUTOFMEMORY;
1451 goto end;
1452 }
1453
1454 for (i=1; i<=count; i++ )
1455 {
1456 (*types)[i-1] = strdupW(MSI_RecordGetString(prec, i));
1457 }
1458
1459 end:
1460 msiobj_release( &prec->hdr );
1461 return r;
1462 }
1463
1464 static void merge_free_rows(MERGETABLE *table)
1465 {
1466 struct list *item, *cursor;
1467
1468 LIST_FOR_EACH_SAFE(item, cursor, &table->rows)
1469 {
1470 MERGEROW *row = LIST_ENTRY(item, MERGEROW, entry);
1471
1472 list_remove(&row->entry);
1473 msiobj_release(&row->data->hdr);
1474 msi_free(row);
1475 }
1476 }
1477
1478 static void free_merge_table(MERGETABLE *table)
1479 {
1480 UINT i;
1481
1482 if (table->labels != NULL)
1483 {
1484 for (i = 0; i < table->numlabels; i++)
1485 msi_free(table->labels[i]);
1486 msi_free(table->labels);
1487 }
1488
1489 if (table->columns != NULL)
1490 {
1491 for (i = 0; i < table->numcolumns; i++)
1492 msi_free(table->columns[i]);
1493 msi_free(table->columns);
1494 }
1495
1496 if (table->types != NULL)
1497 {
1498 for (i = 0; i < table->numtypes; i++)
1499 msi_free(table->types[i]);
1500 msi_free(table->types);
1501 }
1502 msi_free(table->name);
1503 merge_free_rows(table);
1504
1505 msi_free(table);
1506 }
1507
1508 static UINT msi_get_merge_table (MSIDATABASE *db, LPCWSTR name, MERGETABLE **ptable)
1509 {
1510 UINT r;
1511 MERGETABLE *table;
1512 MSIQUERY *mergeview = NULL;
1513
1514 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1515 'F','R','O','M',' ','`','%','s','`',0};
1516
1517 table = msi_alloc_zero(sizeof(MERGETABLE));
1518 if (!table)
1519 {
1520 *ptable = NULL;
1521 return ERROR_OUTOFMEMORY;
1522 }
1523
1524 r = msi_get_table_labels(db, name, &table->labels, &table->numlabels);
1525 if (r != ERROR_SUCCESS)
1526 goto err;
1527
1528 r = MSI_OpenQuery(db, &mergeview, query, name);
1529 if (r != ERROR_SUCCESS)
1530 goto err;
1531
1532 r = msi_get_query_columns(mergeview, &table->columns, &table->numcolumns);
1533 if (r != ERROR_SUCCESS)
1534 goto err;
1535
1536 r = msi_get_query_types(mergeview, &table->types, &table->numtypes);
1537 if (r != ERROR_SUCCESS)
1538 goto err;
1539
1540 list_init(&table->rows);
1541
1542 table->name = strdupW(name);
1543 table->numconflicts = 0;
1544
1545 msiobj_release(&mergeview->hdr);
1546 *ptable = table;
1547 return ERROR_SUCCESS;
1548
1549 err:
1550 msiobj_release(&mergeview->hdr);
1551 free_merge_table(table);
1552 *ptable = NULL;
1553 return r;
1554 }
1555
1556 static UINT merge_diff_tables(MSIRECORD *rec, LPVOID param)
1557 {
1558 MERGEDATA *data = param;
1559 MERGETABLE *table;
1560 MSIQUERY *dbview = NULL;
1561 MSIQUERY *mergeview = NULL;
1562 LPCWSTR name;
1563 UINT r;
1564
1565 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1566 'F','R','O','M',' ','`','%','s','`',0};
1567
1568 name = MSI_RecordGetString(rec, 1);
1569
1570 r = MSI_OpenQuery(data->merge, &mergeview, query, name);
1571 if (r != ERROR_SUCCESS)
1572 goto done;
1573
1574 if (TABLE_Exists(data->db, name))
1575 {
1576 r = MSI_OpenQuery(data->db, &dbview, query, name);
1577 if (r != ERROR_SUCCESS)
1578 goto done;
1579
1580 r = merge_verify_colnames(dbview, mergeview);
1581 if (r != ERROR_SUCCESS)
1582 goto done;
1583
1584 r = merge_verify_primary_keys(data->db, data->merge, name);
1585 if (r != ERROR_SUCCESS)
1586 goto done;
1587 }
1588
1589 r = msi_get_merge_table(data->merge, name, &table);
1590 if (r != ERROR_SUCCESS)
1591 goto done;
1592
1593 data->curtable = table;
1594 data->curview = mergeview;
1595 r = MSI_IterateRecords(mergeview, NULL, merge_diff_row, data);
1596 if (r != ERROR_SUCCESS)
1597 {
1598 free_merge_table(table);
1599 goto done;
1600 }
1601
1602 list_add_tail(data->tabledata, &table->entry);
1603
1604 done:
1605 msiobj_release(&dbview->hdr);
1606 msiobj_release(&mergeview->hdr);
1607 return r;
1608 }
1609
1610 static UINT gather_merge_data(MSIDATABASE *db, MSIDATABASE *merge,
1611 struct list *tabledata)
1612 {
1613 UINT r;
1614 MSIQUERY *view;
1615 MERGEDATA data;
1616
1617 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1618 'F','R','O','M',' ','`','_','T','a','b','l','e','s','`',0};
1619
1620 r = MSI_DatabaseOpenViewW(merge, query, &view);
1621 if (r != ERROR_SUCCESS)
1622 return r;
1623
1624 data.db = db;
1625 data.merge = merge;
1626 data.tabledata = tabledata;
1627 r = MSI_IterateRecords(view, NULL, merge_diff_tables, &data);
1628
1629 msiobj_release(&view->hdr);
1630 return r;
1631 }
1632
1633 static UINT merge_table(MSIDATABASE *db, MERGETABLE *table)
1634 {
1635 UINT r;
1636 MERGEROW *row;
1637 MSIVIEW *tv;
1638
1639 if (!TABLE_Exists(db, table->name))
1640 {
1641 r = msi_add_table_to_db(db, table->columns, table->types,
1642 table->labels, table->numlabels, table->numcolumns);
1643 if (r != ERROR_SUCCESS)
1644 return ERROR_FUNCTION_FAILED;
1645 }
1646
1647 LIST_FOR_EACH_ENTRY(row, &table->rows, MERGEROW, entry)
1648 {
1649 r = TABLE_CreateView(db, table->name, &tv);
1650 if (r != ERROR_SUCCESS)
1651 return r;
1652
1653 r = tv->ops->insert_row(tv, row->data, -1, FALSE);
1654 tv->ops->delete(tv);
1655
1656 if (r != ERROR_SUCCESS)
1657 return r;
1658 }
1659
1660 return ERROR_SUCCESS;
1661 }
1662
1663 static UINT update_merge_errors(MSIDATABASE *db, LPCWSTR error,
1664 LPWSTR table, DWORD numconflicts)
1665 {
1666 UINT r;
1667 MSIQUERY *view;
1668
1669 static const WCHAR create[] = {
1670 'C','R','E','A','T','E',' ','T','A','B','L','E',' ',
1671 '`','%','s','`',' ','(','`','T','a','b','l','e','`',' ',
1672 'C','H','A','R','(','2','5','5',')',' ','N','O','T',' ',
1673 'N','U','L','L',',',' ','`','N','u','m','R','o','w','M','e','r','g','e',
1674 'C','o','n','f','l','i','c','t','s','`',' ','S','H','O','R','T',' ',
1675 'N','O','T',' ','N','U','L','L',' ','P','R','I','M','A','R','Y',' ',
1676 'K','E','Y',' ','`','T','a','b','l','e','`',')',0};
1677 static const WCHAR insert[] = {
1678 'I','N','S','E','R','T',' ','I','N','T','O',' ',
1679 '`','%','s','`',' ','(','`','T','a','b','l','e','`',',',' ',
1680 '`','N','u','m','R','o','w','M','e','r','g','e',
1681 'C','o','n','f','l','i','c','t','s','`',')',' ','V','A','L','U','E','S',
1682 ' ','(','\'','%','s','\'',',',' ','%','d',')',0};
1683
1684 if (!TABLE_Exists(db, error))
1685 {
1686 r = MSI_OpenQuery(db, &view, create, error);
1687 if (r != ERROR_SUCCESS)
1688 return r;
1689
1690 r = MSI_ViewExecute(view, NULL);
1691 msiobj_release(&view->hdr);
1692 if (r != ERROR_SUCCESS)
1693 return r;
1694 }
1695
1696 r = MSI_OpenQuery(db, &view, insert, error, table, numconflicts);
1697 if (r != ERROR_SUCCESS)
1698 return r;
1699
1700 r = MSI_ViewExecute(view, NULL);
1701 msiobj_release(&view->hdr);
1702 return r;
1703 }
1704
1705 UINT WINAPI MsiDatabaseMergeW(MSIHANDLE hDatabase, MSIHANDLE hDatabaseMerge,
1706 LPCWSTR szTableName)
1707 {
1708 struct list tabledata = LIST_INIT(tabledata);
1709 struct list *item, *cursor;
1710 MSIDATABASE *db, *merge;
1711 MERGETABLE *table;
1712 BOOL conflicts;
1713 UINT r;
1714
1715 TRACE("(%d, %d, %s)\n", hDatabase, hDatabaseMerge,
1716 debugstr_w(szTableName));
1717
1718 if (szTableName && !*szTableName)
1719 return ERROR_INVALID_TABLE;
1720
1721 db = msihandle2msiinfo(hDatabase, MSIHANDLETYPE_DATABASE);
1722 merge = msihandle2msiinfo(hDatabaseMerge, MSIHANDLETYPE_DATABASE);
1723 if (!db || !merge)
1724 {
1725 r = ERROR_INVALID_HANDLE;
1726 goto done;
1727 }
1728
1729 r = gather_merge_data(db, merge, &tabledata);
1730 if (r != ERROR_SUCCESS)
1731 goto done;
1732
1733 conflicts = FALSE;
1734 LIST_FOR_EACH_ENTRY(table, &tabledata, MERGETABLE, entry)
1735 {
1736 if (table->numconflicts)
1737 {
1738 conflicts = TRUE;
1739
1740 r = update_merge_errors(db, szTableName, table->name,
1741 table->numconflicts);
1742 if (r != ERROR_SUCCESS)
1743 break;
1744 }
1745 else
1746 {
1747 r = merge_table(db, table);
1748 if (r != ERROR_SUCCESS)
1749 break;
1750 }
1751 }
1752
1753 LIST_FOR_EACH_SAFE(item, cursor, &tabledata)
1754 {
1755 MERGETABLE *table = LIST_ENTRY(item, MERGETABLE, entry);
1756
1757 list_remove(&table->entry);
1758 free_merge_table(table);
1759 }
1760
1761 if (conflicts)
1762 r = ERROR_FUNCTION_FAILED;
1763
1764 done:
1765 msiobj_release(&db->hdr);
1766 msiobj_release(&merge->hdr);
1767 return r;
1768 }
1769
1770 MSIDBSTATE WINAPI MsiGetDatabaseState( MSIHANDLE handle )
1771 {
1772 MSIDBSTATE ret = MSIDBSTATE_READ;
1773 MSIDATABASE *db;
1774
1775 TRACE("%d\n", handle);
1776
1777 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
1778 if( !db )
1779 {
1780 IWineMsiRemoteDatabase *remote_database;
1781
1782 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
1783 if ( !remote_database )
1784 return MSIDBSTATE_ERROR;
1785
1786 IWineMsiRemoteDatabase_Release( remote_database );
1787 WARN("MsiGetDatabaseState not allowed during a custom action!\n");
1788
1789 return MSIDBSTATE_READ;
1790 }
1791
1792 if (db->mode != MSIDBOPEN_READONLY )
1793 ret = MSIDBSTATE_WRITE;
1794 msiobj_release( &db->hdr );
1795
1796 return ret;
1797 }
1798
1799 typedef struct _msi_remote_database_impl {
1800 const IWineMsiRemoteDatabaseVtbl *lpVtbl;
1801 MSIHANDLE database;
1802 LONG refs;
1803 } msi_remote_database_impl;
1804
1805 static inline msi_remote_database_impl* mrd_from_IWineMsiRemoteDatabase( IWineMsiRemoteDatabase* iface )
1806 {
1807 return (msi_remote_database_impl *)iface;
1808 }
1809
1810 static HRESULT WINAPI mrd_QueryInterface( IWineMsiRemoteDatabase *iface,
1811 REFIID riid,LPVOID *ppobj)
1812 {
1813 if( IsEqualCLSID( riid, &IID_IUnknown ) ||
1814 IsEqualCLSID( riid, &IID_IWineMsiRemoteDatabase ) )
1815 {
1816 IUnknown_AddRef( iface );
1817 *ppobj = iface;
1818 return S_OK;
1819 }
1820
1821 return E_NOINTERFACE;
1822 }
1823
1824 static ULONG WINAPI mrd_AddRef( IWineMsiRemoteDatabase *iface )
1825 {
1826 msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
1827
1828 return InterlockedIncrement( &This->refs );
1829 }
1830
1831 static ULONG WINAPI mrd_Release( IWineMsiRemoteDatabase *iface )
1832 {
1833 msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
1834 ULONG r;
1835
1836 r = InterlockedDecrement( &This->refs );
1837 if (r == 0)
1838 {
1839 MsiCloseHandle( This->database );
1840 msi_free( This );
1841 }
1842 return r;
1843 }
1844
1845 static HRESULT WINAPI mrd_IsTablePersistent( IWineMsiRemoteDatabase *iface,
1846 BSTR table, MSICONDITION *persistent )
1847 {
1848 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
1849 *persistent = MsiDatabaseIsTablePersistentW(This->database, table);
1850 return S_OK;
1851 }
1852
1853 static HRESULT WINAPI mrd_GetPrimaryKeys( IWineMsiRemoteDatabase *iface,
1854 BSTR table, MSIHANDLE *keys )
1855 {
1856 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
1857 UINT r = MsiDatabaseGetPrimaryKeysW(This->database, table, keys);
1858 return HRESULT_FROM_WIN32(r);
1859 }
1860
1861 static HRESULT WINAPI mrd_GetSummaryInformation( IWineMsiRemoteDatabase *iface,
1862 UINT updatecount, MSIHANDLE *suminfo )
1863 {
1864 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
1865 UINT r = MsiGetSummaryInformationW(This->database, NULL, updatecount, suminfo);
1866 return HRESULT_FROM_WIN32(r);
1867 }
1868
1869 static HRESULT WINAPI mrd_OpenView( IWineMsiRemoteDatabase *iface,
1870 BSTR query, MSIHANDLE *view )
1871 {
1872 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
1873 UINT r = MsiDatabaseOpenViewW(This->database, query, view);
1874 return HRESULT_FROM_WIN32(r);
1875 }
1876
1877 static HRESULT WINAPI mrd_SetMsiHandle( IWineMsiRemoteDatabase *iface, MSIHANDLE handle )
1878 {
1879 msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
1880 This->database = handle;
1881 return S_OK;
1882 }
1883
1884 static const IWineMsiRemoteDatabaseVtbl msi_remote_database_vtbl =
1885 {
1886 mrd_QueryInterface,
1887 mrd_AddRef,
1888 mrd_Release,
1889 mrd_IsTablePersistent,
1890 mrd_GetPrimaryKeys,
1891 mrd_GetSummaryInformation,
1892 mrd_OpenView,
1893 mrd_SetMsiHandle,
1894 };
1895
1896 HRESULT create_msi_remote_database( IUnknown *pOuter, LPVOID *ppObj )
1897 {
1898 msi_remote_database_impl *This;
1899
1900 This = msi_alloc( sizeof *This );
1901 if (!This)
1902 return E_OUTOFMEMORY;
1903
1904 This->lpVtbl = &msi_remote_database_vtbl;
1905 This->database = 0;
1906 This->refs = 1;
1907
1908 *ppObj = This;
1909
1910 return S_OK;
1911 }